一、异步委托开启线程
Action<int, int> a = 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类开启线程
new Thread(() => { DTTEST(); }) { IsBackground = true }.Start(); new Thread(() => { DTTEST(); }) { IsBackground = true }.Start(); new Thread(() => { DTTEST(); }) { IsBackground = true }.Start(); Thread.Sleep(10000); static private void DTTEST() { Console.WriteLine($"测试并行调用{DateTime.Now}"); }
或者
Thread thread = new Thread(() => { while (true) { Thread.Sleep(1000); DTTEST(); } }); thread.Start();
三、通过线程池开启线程
var param = "哈哈"; ThreadPool.QueueUserWorkItem(obj => { // DTTEST(param); CallbackDemoViod(obj); }, param); ThreadPool.QueueUserWorkItem((o) => { DTTEST(param); }); private static void CallbackDemoViod(object obj) { //以下不catch异常就会导致闪退 try { Console.WriteLine(obj.ToString()); } catch (Exception ex) { Console.WriteLine(ex); } } static private void DTTEST(string a) { try { Console.WriteLine(a); } catch (Exception ex) { Console.WriteLine(ex); } }
或者
var param = "哈哈"; ThreadPool.QueueUserWorkItem(CallbackDemoViod, param);//这种写法方法体参数必须为object private static void CallbackDemoViod(object obj) { //以下不catch异常就会导致闪退 try { Console.WriteLine(obj.ToString()); } catch (Exception ex) { Console.WriteLine(ex); } }
或者
var param = "哈哈"; WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false) }; ThreadPool.QueueUserWorkItem((o) => { DTTEST(param); ((AutoResetEvent)o).Set(); }, waitHandles[0]); ThreadPool.QueueUserWorkItem((o) => { DTTEST(param); ((AutoResetEvent)o).Set(); }, waitHandles[1]); ThreadPool.QueueUserWorkItem((o) => { DTTEST(param); ((AutoResetEvent)o).Set(); }, waitHandles[2]); WaitHandle.WaitAll(waitHandles); static private void DTTEST(string a) { try { Console.WriteLine(a); } catch (Exception ex) { Console.WriteLine(ex); } }
4、通过任务开启线程
4.1通过Task
Task wt1 = Task.Run(() => { DTTEST(); }); Task wt2 = Task.Run(() => { DTTEST(); }); Task wt3 = Task.Run(() => { DTTEST(); }); var wtasks = new Task[] { wt1, wt2, wt3 }; Task.WaitAll(wtasks); static private void DTTEST() { Console.WriteLine($"测试并行调用{DateTime.Now}"); }
int val = 5; Task.Factory.StartNew(() => { MessageBox.Show("测试StartNew:无参数"); }); Task.Factory.StartNew(a => { MessageBox.Show("测试StartNew:参数值" + (int)a); }, val);
5、Invoke实现
Parallel.Invoke( () => { DTTEST(); }, () => { DTTEST(); }, () => { DTTEST(); }, () => { DTTEST(); }, () => { DTTEST(); } );