正确途径暂时停止工作线程线程、途径、正确、工作

由网友(薄荷味白衬衫)分享简介:我有一个工作线程可以是活动的时间短脉冲和闲置的时间休息。我想放线程休眠,然后在需要的时候醒了。I have a worker thread that may be active for short bursts of time and idle for rest of the time. I'm thinking t...

我有一个工作线程可以是活动的时间短脉冲和闲置的时间休息。我想放线程休眠,然后在需要的时候醒了。

I have a worker thread that may be active for short bursts of time and idle for rest of the time. I'm thinking to put the thread to sleep and then awake it when needed.

为了这个,我应该知道的任何其他建议?

Any additional recommendations for this I should be aware of?

谢谢!

这是在C#/。NET4

推荐答案

只需使用一个事件暂停工作线程:复位 - 暂停,设置 - 取消暂停(工作)状态

Just use an event to pause the worker thread: reset - paused, set - unpaused (working) state.

下面是在草稿版本的code演示的方法。

Here is the draft version of code that demonstrates the approach.

class Worker
{
    private Thread _thread;

    // Un-paused by default.
    private ManualResetEvent _notToBePaused = new ManualResetEvent(true);

    public Worker()
    {
        _thread = new Thread(Run)
            {
                IsBackground = true
            };
    }

    /// <summary>
    /// Thread function.
    /// </summary>
    private void Run()
    {
        while (true)
        {
            // Would block if paused!
            _notToBePaused.WaitOne();

            // Process some stuff here.
        }
    }

    public void Start()
    {
        _thread.Start();
    }

    public void Pause()
    {
        _notToBePaused.Reset();
    }

    public void UnPause()
    {
        _notToBePaused.Set();
    }
}
阅读全文

相关推荐

最新文章