- 主线程的代码先执行
- 再执行子线程
- 最后执行主线程的方法
其实还是主线程执行,再New了一个新线程,然后大家各干个的事了。
public delegate void Entrust(string str); static void Main(string[] args) { Entrust callback = new Entrust(ShowMesage); //把方法赋值给委托 Thread th = new Thread(p=> SendResult(callback,"xxx","abc")); th.IsBackground = true; th.Start(callback);//将委托传递到子线程中 Console.WriteLine("我是主程序里输出的"); Console.ReadKey(); } private static void SendResult(object obj, string str, string strResult) { try { //注意:线程的参数是object类型 for (int i = 1; i <= 10; i++) { Console.WriteLine("子线程循环操作第 {0} 次", i); Thread.Sleep(500); } throw new Exception("子线程报错了"); } catch (Exception ex) { Entrust callback = obj as Entrust;//强转为委托 callback("我是子线程,我执行完毕了,通知主线程:"+ex.Message); } } private static void ShowMesage(string str) { Console.WriteLine(str); }