直接上代码
1.BeginInvoke和EndInvoke方式
private static void BeginInvoke1() { Func<int,string> fun = Todo; for (int i = 0; i < 5; i++) { //fun.BeginInvoke(i,TodoCallBack, fun); /* 异步调用委托BeginInvoke * handler.EndInvoke(x)为执行委托的结果 */ fun.BeginInvoke(i, x => { Func<int, string> handler = x.AsyncState as Func<int, string>; //str:为异步调用的返回值 string str=handler.EndInvoke(x); Console.WriteLine(str); }, fun); } }
第二种Thread
private static void Test(object i) { Console.WriteLine(i.ToString()); } private static void Thread1() { //可以传入一个object值,不能接收返回值 System.Threading.Thread t = new System.Threading.Thread(Test); t.Start(10); }
线程池的启用
private static void ThreadPools() { System.Threading.ThreadPool.QueueUserWorkItem(x => { Console.WriteLine("线程池启动"+x); },"ss"); }
第三种:Task,这个是在.net4.0以后才出来的
private static void TaskFac() { //工厂属性的调用方式 Task t = Task.Factory.StartNew(x => { Console.WriteLine("测试"+x); },"taskFac"); }
//无参数下发
System.Threading.Tasks.Task.Factory.StartNew(()=>{
new PushWeiXin().RefundNotify(drawbackInfo.orderno,drawbackInfo.username, drawbackInfo.drawback_reason);
});
private static void TestTask() { //简单的调用方式 Task t = new Task((x) => { System.Threading.Thread.Sleep(1000); Console.WriteLine("测试"+x); },"task"); t.Start(); //t.Wait();//让主线程执行完成后执行后面的代码 Console.WriteLine("主线程完成"); }