开启线程的四种方式

一、异步委托开启线程
        static void Main(string[] args)
        {
            Action<int, int> a = add;
            a.BeginInvoke(3, 4, null,null);
            Console.WriteLine("main()");
            Console.ReadKey();
        }
        static void add(int a, int b)
        {
            Console.WriteLine(a + b);
        }

![在这里插入图片描述](https://img-blog.csdnimg.cn/20191128153752879.png

二、通过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("下载完成!");
		}

在这里插入图片描述

四、通过任务开启线程

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("下载完成!");
		}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值