ill*_*ant 1 c# multithreading delegates
假设我们有一些像这样的简单代码:
private static void Main()
{
Console.WriteLine("Main thread {0}\n", Thread.CurrentThread.ManagedThreadId);
Action asyncCaller1 = () => LongPerfomingTask(5);
Action asyncCaller2 = () => LongPerfomingTask(3);
var asyncResult1 = asyncCaller1.BeginInvoke(null, null);
var asyncResult2 = asyncCaller2.BeginInvoke(null, null);
asyncResult1.AsyncWaitHandle.WaitOne();
asyncResult2.AsyncWaitHandle.WaitOne();
Console.WriteLine("Done");
}
private static void LongPerfomringTask(int seconds)
{
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("Thread {0} finished execution", Thread.CurrentThread.ManagedThreadId);
}
Run Code Online (Sandbox Code Playgroud)
Delegate.BeginInvoke()不会创建一个线程,它在调用者的线程中处于空闲状态时执行代码,对吧?那么,为什么这个示例应用程序的输出是这样的:
Main thread 1
Thread 4 finished execution
Thread 3 finished execution
Done
Run Code Online (Sandbox Code Playgroud)
不,Delegate.BeginInvoke使用线程池.总是.没有"在闲置时在调用者的线程中执行"的概念,除非您考虑将任务添加到UI消息队列中......您是否与Control.BeginInvoke/ Dispatcher.BeginInvoke?
在这种情况下,你有一个控制台应用程序 - 开始时没有消息.
| 归档时间: |
|
| 查看次数: |
6822 次 |
| 最近记录: |