直接贴代码了:
class Program { static void Main(string[] args) { string result = null; Console.WriteLine(string.Format("当前时间:{0},现在是主线程,准备开始多线程...", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); AutoResetEvent resetEvent = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(state => { result = DoSomething(); resetEvent.Set(); })); resetEvent.WaitOne(); Console.WriteLine("多线程返回的值:" + result); Console.WriteLine(string.Format("当前时间:{0},多线程执行完毕,回到主线程。", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); } static string DoSomething() { Thread.Sleep(3000); return "Finished"; } }
运行截图:
关于 委托的 BeginInvoke 方法
直接贴代码了:
class Program { static void Main(string[] args) { string result = null; Console.WriteLine(string.Format("当前时间:{0},现在是主线程,准备开始多线程...", DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"))); var doSomgthingDelegate = new Func<string>(DoSomething); var asyncResult = doSomgthingDelegate.BeginInvoke(new AsyncCallback(aresult => { result = doSomgthingDelegate.EndInvoke(aresult); }), null); asyncResult.AsyncWaitHandle.WaitOne(); Console.WriteLine("多线程返回的值:" + result); Console.WriteLine(string.Format("当前时间:{0},多线程执行完毕,回到主线程。", DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"))); } static string DoSomething() { Thread.Sleep(3000); return "Finished"; } }
运行截图(注意:多线程返回的值为 NULL,有问题):
谢谢浏览!