c# Delegate.BeginInvoke() 和线程 ID

发布于 2024-10-30 16:19:46 字数 909 浏览 1 评论 0原文

假设我们有一些像这样的简单代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转身以后 2024-11-06 16:19:46

不,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 with Control.BeginInvoke / Dispatcher.BeginInvoke?

In this case you've got a console app - there's no message pumping going on to start with.

高冷爸爸 2024-11-06 16:19:46

@taras.roshko:这里有一个资源可以增强您对 ThreadPool 的理解:
线程章节

@taras.roshko: Here's a resource to boost your understanding of ThreadPool:
Chapter on Threading

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文