开发者

Can I wait for a specific background thread finish, then another background thread starts? [closed]

开发者 https://www.devze.com 2023-01-20 11:04 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be开发者_开发问答 reopened, visit the help center. Closed 10 years ago.

Can I wait for a specific background thread finish, then another background thread starts?


In .NET 4, you can use Task instead of threads, and then use continuations to achieve your goals:

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

var secondTask = firstTask.ContinueWith( t => PerformSecondAction(); );

In .NET <=3.5, the options vary. The best is often to use a WaitHandle to signal your second task. The first background thread will need to signal the wait handle when it's complete:

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();
      });


Sure. Have the first thread launch the second thread, or set some sort of flag telling the hosting app to start the second thread. Of course, I have to ask: if these threads always run sequentially, why create a second thread at all instead of performing all of your work in the first thread?


Yes.

And if you provide more information, we can provide more detail in the answer.

In general, you set up a communication system (a message queue, Event, or delegate) that is used to signal that a process/step/thread is done. When that happens, start up the next thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号