我有一个工作线程,它可能会在短时间内处于事件状态,而在其余时间处于空闲状态。我正在考虑让线程休眠,然后在需要时唤醒它。
关于此我应该注意的任何其他建议?
谢谢!
- 这是在 C#/.NET4 中
最佳答案
您可能不应该使用持久工作线程——使用线程池。这正是它的目的。
ThreadPool.QueueUserWorkItem(() => {
// My temporary work here
});
如果你坚持要有一个持久的工作线程,让它运行这个:
// This is our latch- we can use this to "let the thread out of the gate"
AutoResetEvent threadLatch = new AutoResetEvent(false);
// The thread runs this
public void DoBackgroundWork() {
// Making sure that the thread is a background thread
// ensures that the endless loop below doesn't prevent
// the program from exiting
Thread.IsBackground = true;
while (true) {
// The worker thread will get here and then block
// until someone Set()s the latch:
threadLatch.WaitOne();
// Do your work here
}
}
// To signal the thread to start:
threadLatch.Set();
另请注意,如果此后台线程要与用户界面进行交互,您将需要相应地调用或开始调用。参见 http://weblogs.asp.net/justin_rogers/pages/126345.aspx
关于c# - 临时挂起工作线程的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10047571/