C# 异步/线程

参考:https://www.cnblogs.com/wcrBlog/p/11690460.html

 

   
public static void
BeginCollection() { //var manualRestEventA = new ManualResetEvent(false); //Thread thread = new Thread(ThreadMethod); //执行的必须是无返回值的方法 //thread.Name = "子线程1"; //var thread2 = new Thread(ThreadMethod); //thread2.Name = "子线程2"; //thread.Start("子线程1"); //在此方法内传递参数,类型为object,发送和接收涉及到拆装箱操作 //thread2.Start("子线程2"); //manualRestEventA.WaitOne(); var manualResetEventList=new List<ManualResetEvent>(); for (var i = 0; i < 10; i++) { var mre=new ManualResetEvent(false); manualResetEventList.Add(mre); ThreadPool.QueueUserWorkItem(ThreadMethod, new {id = i, url = "www",mre}); } WaitHandle.WaitAll(manualResetEventList.ToArray()); Console.WriteLine("主线程结束"); } public static void ThreadMethod(object parameter) //方法内可以有参数,也可以没有参数 { Console.WriteLine($"parameter:{parameter} { ((dynamic)parameter).url}"); Console.WriteLine("{0}开始执行。", ((dynamic)parameter).id); var result = 0; for (int i = 0; i < 1000000000; i++) { result += i; } ((dynamic) parameter).mre.Set(); Console.WriteLine($"线程{((dynamic)parameter).id}执行完毕"); }

 

posted @ 2020-11-06 17:43  超难微猫  阅读(110)  评论(0编辑  收藏  举报