c#Delegate.BeginInvoke()和线程ID

时间:2011-04-05 14:38:11

标签: 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);
}

Delegate.BeginInvoke()不会创建一个线程,它在调用者的线程中处于空闲状态时执行代码,对吧?那么,为什么这个示例应用程序的输出是这样的:

Main thread 1

Thread 4 finished execution
Thread 3 finished execution
Done

2 个答案:

答案 0 :(得分:6)

不,Delegate.BeginInvoke使用线程池。总是。除非您考虑将任务添加到UI消息队列中,否则没有“在闲置时在调用者的线程中执行”的概念......您是否对Control.BeginInvoke / Dispatcher.BeginInvoke感到困惑?

在这种情况下,你有一个控制台应用程序 - 开始时没有消息流动。

答案 1 :(得分:0)

@ taras.roshko:这是一个增强您对ThreadPool的理解的资源: Chapter on Threading

相关问题