c# Delegate.BeginInvoke() 和线程 ID
假设我们有一些像这样的简单代码:
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);
}
Delegate.BeginInvoke() 不会创建线程,它会在调用者线程处于空闲状态时执行代码,对吧?那么,为什么这个示例应用程序的输出是这样的:
Main thread 1
Thread 4 finished execution
Thread 3 finished execution
Done
let's say we have some simple code like this :
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);
}
Delegate.BeginInvoke() does not create a thread, It's executing code in a caller's thread when it is in idle state, right?So, why the output of this sample application is like this :
Main thread 1
Thread 4 finished execution
Thread 3 finished execution
Done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
Delegate.BeginInvoke
使用线程池。总是。没有“在调用者线程空闲时执行”的概念,除非您正在考虑将任务添加到 UI 消息队列...您是否对Control.BeginInvoke
/Dispatcher 感到困惑.BeginInvoke
?在本例中,您有一个控制台应用程序 - 首先没有消息泵送。
No,
Delegate.BeginInvoke
uses the thread pool. Always. There's no concept of "executing in the caller's thread when it's idle" unless you're thinking of adding tasks to a UI message queue... were you getting confused withControl.BeginInvoke
/Dispatcher.BeginInvoke
?In this case you've got a console app - there's no message pumping going on to start with.
@taras.roshko:这里有一个资源可以增强您对 ThreadPool 的理解:
线程章节
@taras.roshko: Here's a resource to boost your understanding of ThreadPool:
Chapter on Threading