【问题标题】:How do i ensure statement gets executed after all the threads have completed execution我如何确保在所有线程完成执行后执行语句
【发布时间】:2013-10-12 13:10:47
【问题描述】:

假设我的主线程调用了一个循环,该循环创建了新线程并在其他函数上启动它们。

for (int i = 0; i < numberOfThreads; i++)
{
        Thread thread = new Thread(start);
        thread.Start();
}
call_This_Function_After_All_Threads_Have_Completed_Execution();

我如何确保只有在所有其他线程完成执行后才调用我的方法。

【问题讨论】:

标签: c# .net multithreading


【解决方案1】:

您可以使用 AutoResetEvent-s。声明一个所有线程都可以到达的 AutoResetEvent 数组。

AutoResetEvent[] events = new AutoResetEvent[numberOfThreads];

像这样启动线程:

for (int i = 0; i < numberOfThreads; i++)
{
    events[i] = new AutoResetEvent(false);
    Thread thread = new Thread(start);
    thread.Start(i);
}
WaitHandle.WaitAll(events);
call_This_Function_After_All_Threads_Have_Completed_Execution();

最后别忘了在线程中调用 Set() 方法:

 void start(object i)
 {
       //... do work
       events[(int) i].Set();
 }

【讨论】:

    猜你喜欢
    • 2012-12-04
    • 2022-01-10
    • 2011-10-25
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多