标签:begin obj 表达式 ack 调用 back style alt vat
Func<int, int> a = Test; IAsyncResult ar = a.BeginInvoke(20, OnCallBack, a);//倒数第二个参数是一个委托类型的参数,表示回调函数,当线程结束时会调用这个委托指向的方法;倒数第一个参数用来给回调函数传递数据;通过ar获取数据a
1. thread参数为静态方法
static void Downloadfile() { Console.WriteLine("开始下载" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.WriteLine("下载完成"); } static void Main(string[] args) { Thread t = new Thread(Downloadfile); t.Start(); Console.WriteLine("main"); Console.ReadKey(); }
2. lamda表达式
1 Thread t = new Thread(() => 2 { 3 Console.WriteLine("开始下载" + Thread.CurrentThread.ManagedThreadId); 4 Thread.Sleep(2000); 5 Console.WriteLine("下载完成"); 6 }); 7 t.Start();
3. Thread参数为普通方法
1 class Program 2 { 3 static void Downloadfile(object filename) 4 { 5 Console.WriteLine("开始下载" + filename+ Thread.CurrentThread.ManagedThreadId); 6 Thread.Sleep(2000); 7 Console.WriteLine("下载完成"+filename); 8 } 9 10 static void Main(string[] args) 11 { 12 //Thread t = new Thread(() => 13 //{ 14 15 // Console.WriteLine("开始下载" + Thread.CurrentThread.ManagedThreadId); 16 // Thread.Sleep(2000); 17 // Console.WriteLine("下载完成"); 18 //}); 19 //Thread t = new Thread(Downloadfile); 20 MyThread my = new MyThread("xxx.bt", "http://www.xxx.bbs"); 21 Thread t = new Thread(my.DownFile); 22 t.Start(); 23 Console.WriteLine("main"); 24 Console.ReadKey(); 25 } 26 }
1 class MyThread 2 { 3 private string filename; 4 private string filepath; 5 public MyThread(string fileName, string filePath) 6 { 7 this.filename = fileName; 8 this.filepath = filePath; 9 } 10 11 public void DownFile() 12 { 13 Console.WriteLine("开始下载" + filepath + filename); 14 Thread.Sleep(2000); 15 Console.WriteLine("下载完成"); 16 } 17 18 } 19 }
1 class Program 2 { 3 static void ThreadMethod(object state) 4 { 5 Console.WriteLine("线程开始"+Thread.CurrentThread.ManagedThreadId); 6 Thread.Sleep(2000); 7 Console.WriteLine("线程结束"); 8 } 9 static void Main(string[] args) 10 { 11 ThreadPool.QueueUserWorkItem(ThreadMethod); 12 ThreadPool.QueueUserWorkItem(ThreadMethod); 13 ThreadPool.QueueUserWorkItem(ThreadMethod); 14 ThreadPool.QueueUserWorkItem(ThreadMethod); 15 ThreadPool.QueueUserWorkItem(ThreadMethod); 16 Console.ReadKey(); 17 } 18 }
1. 通过Task创建
1 class Program 2 { 3 static void ThreadMethod() 4 { 5 Console.WriteLine("任务开始" + Thread.CurrentThread.ManagedThreadId); 6 Thread.Sleep(2000); 7 Console.WriteLine("任务结束"); 8 } 9 10 static void Main(string[] args) 11 { 12 Task t = new Task(ThreadMethod); 13 t.Start(); 14 Console.WriteLine("main"); 15 Console.ReadKey(); 16 } 17 }
2. 通过TaskFactory创建
TaskFactory tf = new TaskFactory(); tf.StartNew(ThreadMethod);
tf.StartNew(ThreadMethod);
tf.StartNew(ThreadMethod);
标签:begin obj 表达式 ack 调用 back style alt vat
原文地址:https://www.cnblogs.com/wxhao/p/13604924.html