c# - 临时挂起工作线程的正确方法

标签 c# .net multithreading sleep worker

我有一个工作线程,它可能会在短时间内处于事件状态,而在其余时间处于空闲状态。我正在考虑让线程休眠,然后在需要时唤醒它。

关于此我应该注意的任何其他建议?

谢谢!

  • 这是在 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/

相关文章:

ruby - popen 内的超时有效,但超时内的 popen 无效?

Java同步问题

c# - HttpClient.GetAsync 永远不会在 Xamarin.Android 上返回

.net - C# 中的低级编程

c# - 我如何知道 C# 中 BinaryReader 的当前偏移量?

c# - .NET 外部 dll 引用检查

.net - 如何加载在 GAC 中注册的混合程序集?

c++ - 使用notify all进行多次等待

c# - SetConsoleMode 失败并为零,lasterror = 0

C# 如何在反向字节数组中查找字节数组?