我可以等待特定的后台线程完成,然后另一个后台线程启动吗?

Ala*_*lan 0 .net multithreading

我可以等待特定的后台线程完成,然后另一个后台线程启动吗?

Ree*_*sey 6

在.NET 4中,您可以使用Task而不是线程,然后使用continuation来实现您的目标:

var firstTask = Task.Factory.StartNew( () => PerformSomeLongRunningAction(); );

var secondTask = firstTask.ContinueWith( t => PerformSecondAction(); );
Run Code Online (Sandbox Code Playgroud)

在.NET <= 3.5中,选项有所不同.最好的方法是使用WaitHandle来表示你的第二个任务.第一个后台线程需要在等待句柄完成时发出信号:

var mre = new ManualResetEvent(false);

ThreadPool.QueueUserWorkItem( o =>
      {
           PerformSomeLongRunningAction();
           mre.Set(); // Signal to second thread that it can continue
      });

ThreadPool.QueueUserWorkItem( o =>
      {
           mre.WaitOne(); // Wait for first thread to finish
           PerformSecondAction();
      });
Run Code Online (Sandbox Code Playgroud)