最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C#开启线程的四种方式示例详解
时间:2022-06-25 07:40:34 编辑:袖梨 来源:一聚教程网
一、异步委托开启线程
public static void Main(string[] args){ Actiona=add; a.BeginInvoke(3,4,null,null);//前两个是add方法的参数,后两个可以为空 Console.WriteLine("main()"); Console.ReadKey(); } static void add(int a,int b){ Console.WriteLine(a+b); }
运行结果:
如果不是开启线程,像平常一样调用的话,应该先输出7,再输出main()
二、通过thread类开启线程
using System; using System.Threading; public static void Main(string[] args){ Thread t=new Thread(DownLoadFile_My);//创建了线程还未开启 t.Start("http://abc/def/**.mp4");//用来给函数传递参数,开启线程 Console.WriteLine("main()"); Console.ReadKey(); } //thread开启线程要求:该方法参数只能有一个,且是object类型 static void DownLoadFile_My(object filePath){ Console.WriteLine("开始下载:"+filePath); Thread.Sleep(2000); Console.WriteLine("下载完成!"); }
运行结果:
三、通过线程池开启线程
public static void Main(string[] args){ ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); ThreadPool.QueueUserWorkItem(DownLoadFile_My); Console.WriteLine("main()"); Console.ReadKey(); } static void DownLoadFile_My(object state){ Console.WriteLine("开始下载... 线程ID:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.WriteLine("下载完成!"); }
运行结果:
4、通过任务开启线程
1>Task开启线程
using System; using System.Threading; using System.Threading.Tasks; public static void Main(string[] args){ Task t=new Task(DownLoadFile_My); t.Start(); Console.WriteLine("main()"); Console.ReadKey(); } static void DownLoadFile_My( ){ Console.WriteLine("开始下载... 线程ID:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.WriteLine("下载完成!"); }
运行结果:
2>TaskFactory开启线程
public static void Main(string[] args){ TaskFactory tf=new TaskFactory(); tf.StartNew(DownLoadFile_My); Console.WriteLine("main()"); Console.ReadKey(); } static void DownLoadFile_My( ){ Console.WriteLine("开始下载... 线程ID:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.WriteLine("下载完成!"); }
运行结果:
相关文章
- 崩坏星穹铁道灵之珠泪有什么用-崩坏星穹铁道灵之珠泪用法介绍 08-09
- 阴阳师山兔竞速怎么玩-阴阳师山兔竞速阵容推荐2025 08-09
- 晴空之下深邃隧道第1区怎么通关-晴空之下深邃隧道第1区通关攻略 08-09
- 决战平安京零真技能怎么样-决战平安京零真技能介绍 08-09
- 异环日蚀任务怎么完成-异环日蚀任务完成攻略指南 08-09
- 第五人格幽隧中的密约活动怎么玩-第五人格幽隧中的密约活动介绍 08-09