正确途径暂时停止工作线程 [英] Proper Approach for Temporarily Suspending a Worker Thread

查看:215
本文介绍了正确途径暂时停止工作线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于正确途径暂时停止工作线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆