如何正确终止工作线程在C# [英] How to terminate a worker thread correctly in c#

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

问题描述

问题陈述

我有一个工作线程,基本上扫描一个文件夹,进入该文件中,然后睡了而。扫描操作可能需要2-3秒而不是更多。我正在寻找一种方法来阻止优雅这个线程。

I have a worker thread that basically scans a folder, going into the files within it, and then sleeps for a while. The scanning operation might take 2-3 seconds but not much more. I'm looking for a way to stop this thread elegantly.

澄清:我想停止线程,而它的睡觉的,而不是当它的扫描的。然而,问题是,我不知道什么是线程的当前状态。如果它睡觉,我希望它立即退出。如果是扫描,我希望它退出它试图阻止的时刻。

Clarification: I want to stop the thread while it's sleeping, and not while it's scanning. However, the problem is that I do not know what is the current state of the thread. If it's sleeping I want it to exit immediately. If it's scanning, I want it to exit the moment it tries to block.

是在一个解决方案尝试

起初我使用休眠和中断。后来我发现,中断并没有真正中断睡眠 - 它只有当线程试图进入睡眠的作品。

At first I was using Sleep and Interrupt. Then I found out that Interrupt doesn't really interrupt the Sleep - it only works when the threads TRIES to go into sleeping.

所以我切换到监控等待和放大器;脉冲。后来我发现,当我在等待其实是脉冲才起作用。所以现在我有一个线程这看起来像:

So I switched to Monitor Wait&Pulse. Then I found out that the Pulse only works when I'm actually in the Wait. So now I have a thread which looks like that:

while (m_shouldRun)
{
    try
    {
        DoSomethingThatTakesSeveralSeconds();
        lock (this)
        {
            Monitor.Wait(this, 5000);
        }
    }
    catch (ThreadInterruptedException)
    {
        m_shouldRun = false;
    }
}

和现在我需要我的手艺停止功能。于是我开始用:

And now I need to craft my Stop function. So I started with:

public void Stop()
{
    m_shouldRun = false;
    lock (this)
    {
        Monitor.Pulse(this);
    }
    thread.Join();
}



但是,这并不工作,因为我可以在线程进行工作涌动(虽然它不是等待)。所以我加了中断:

But this doesn't work because I may be pulsing while the thread works (while it's not waiting). So I added Interrupt:

public void Stop()
{
    m_shouldRun = false;
    thread.Interrupt();
    lock (this)
    {
        Monitor.Pulse(this);
    }
    thread.Join();
}



另一种选择是使用

Another option is to use:

public void Stop()
{
    m_shouldRun = false;
    while (!thread.Join(1000))
    {
        lock (this)
        {
            Monitor.Pulse(this);
        }
    }
}



问题

什么是首选的方法? ?是否有这是优选的第三方法

What is the preferred method? Is there a third method which is preferable?

推荐答案

另一种替代方法是使用事件:

Another alternative is to use events:

private ManualResetEvent _event = new ManualResetEvent(false);


public void Run() 
{
 while (true)
 {
    DoSomethingThatTakesSeveralSeconds();
    if (_event.WaitOne(timeout))
      break;
 }
}

public void Stop() 
{
   _event.Set();
   thread.Join();
}

这篇关于如何正确终止工作线程在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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