如何在继续之前等待线程完成?

Bri*_*tle 11 c# multithreading compact-framework

我有一些代码用于在.NET CF 2.0上启动一个线程:

ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
Run Code Online (Sandbox Code Playgroud)

如果我在循环中调用它,则项目完全无序.如何引入等待t.Start(),以便在代码继续之前线程上的工作完成?BeginInvoke/EndInvoke比手动创建线程更适合这个吗?

Dom*_*ney 11

您需要在线程上强加多少订单?如果你只是需要在循环中开始的所有工作在代码继续之前完成,但你不关心循环中的工作顺序,那么调用Join就是答案.要向Kevin Kenny的答案添加更多细节,您应该在循环调用Join .这意味着您将需要一个集合来保存对您启动的线程的引用:

// Start all of the threads.
List<Thread> startedThreads = new List<Thread>();
foreach (...) {
  Thread thread = new Thread(new ThreadStart(MyMethod));
  thread.Start();
  startedThreads.Add(thread);
}

// Wait for all of the threads to finish.
foreach (Thread thread in startedThreads) {
  thread.Join();
}
Run Code Online (Sandbox Code Playgroud)

相反,如果你在循环中调用Join,结果基本上与完全不使用线程相同.循环体的每次迭代都会创建并启动一个线程,然后立即加入它并等待它完成.

如果各个线程产生一些结果(例如,在日志中写入消息),则消息可能仍然无序出现,因为线程之间没有协调.通过将它们与Monitor协调,可以让线程按顺序输出结果.


oll*_*ant 5

等待线程完成的另一种方法是使用AutoResetEvent.

private readonly AutoResetEvent mWaitForThread = new AutoResetEvent(false);

private void Blah()
{
    ThreadStart tStart = new ThreadStart(MyMethod);
    Thread t = new Thread(tStart);
    t.Start();

    //... (any other things)
    mWaitForThread.WaitOne();
}

private void MyMethod()
{
     //... (execute any other action)
     mWaitForThread.Set();
}
Run Code Online (Sandbox Code Playgroud)