c# - Thread.Interrupt 不工作

标签 c# multithreading

为什么我的Thread.Interrupt不工作?

执行中断的代码:

public void Stop()
{
    const string LOG_SOURCE = "ProcessingDriver";

    if (_Enabled)
    {
        try
        {
            RequestProcessor.Disable();
            if (ProcessingThread != null)
            {
                ProcessingThread.Interrupt();
                ProcessingThread.Join();
            }
        }
        catch (Exception ex)
        {
            WriteLog(LOG_SOURCE, ex);
        }
    }
}

我希望停止的代码:

private void ProcessRequests()
{
    const string LOG_SOURCE = "ProcessRequests";
    try
    {
        ProcessingThread = Thread.CurrentThread;
        while (!_Disposed)
        {
            _ProcessingWaitHandle.WaitOne();
            int count = GetRequestCount();
            while (count > 0)
            {
                try
                {
                    ExportRequest er = GetRequest();
                    ProcessRequest(er);
                }
                catch (ThreadInterruptedException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    WriteLog(LOG_SOURCE,
                         ex);
                    WriteLog(LOG_SOURCE,
                        "Request Failed.");
                }
                //Suspend to catch interupt
               Thread.Sleep(1);
                count = GetRequestCount();
            }
        }
    }
    catch (ThreadInterruptedException)
    {
        WriteLog(LOG_SOURCE,
            "Interupted. Exiting.", LogType.Info);
    }
    catch (Exception critEx)
    {
        //Should never get here
        WriteLog(LOG_SOURCE, critEx);
        WriteLog(LOG_SOURCE,
            "Serious unhandled error.  Please restart.", LogType.Critical);
    }
}

我已经逐步完成了代码。我可以看到中断被调用( sleep 或等待不是当时的事件命令),我可以看到 sleep 被调用,但没有抛出中断错误(无论是在 sleep 上,还是在 WaitOne 上,即使线程在 WaitOne 上阻塞)。

我做错了什么?

注意:.Net 2.0

最佳答案

嗯...它看起来确实应该工作,但我建议您首先不要使用 Interrupt。使用事件和/或 Monitor.Wait/Pulse 告诉线程您要停止。这是一种通常更简单的方法,并且可以让工作线程更好地控制有序停止。

关于c# - Thread.Interrupt 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468014/

相关文章:

c# - 当前上下文中不存在名称 LayoutRoot

c# - 如何在构造函数中包含 Visual Studio 在设计时不会执行的代码?

c++ - Eigen 库 : Is writing to multiple columns concurrently safe?

java - Server EndPoint for WebSocket Java API 中的 volatile 变量?

java - 具有执行器框架的多个任务

c# - 在数据库中存储动态JSON数据并通过键值搜索

c# - 为什么我在本地声明的变量在 finally block 中没有被识别?

c# - 如何在 C# 中检索 BindingNavigator.PositionItem 的值?

c++ - std::thread 不是使用 Eclipse Kepler MinGW 命名空间 std 的成员

C# 使用线程关闭程序/表单