7

我是一名 Java 程序员,被要求对 C# 应用程序进行一些更改。我已经使用 C# 一个星期了,我终于达到了查看文档无济于事的地步,当我用谷歌搜索时也找不到解决方案。

在这种情况下,我有一个 Windows 服务来处理到达 MSMQ 的消息。当收到一条消息时,当前正在侦听的线程会拾取它并开始执行需要几秒钟的操作。

public void Start()
{
    this.listen = true;
    for (int i = 0; i < Constants.ThreadMaxCount; i++)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartListening), i);
    }
    ...

private void StartListening(Object threadContext)
{

    int threadId = (int)threadContext;
    threads[threadId] = Thread.CurrentThread;
    PostRequest postReq;
    while(this.listen)
    {
        System.Threading.Monitor.Enter(locker);
        try
        {

            postReq = GettingAMessage();
        }
        finally
        {
            System.Threading.Monitor.Exit(locker);
        }
    }
    ...
}

GettingAMessage() 有以下几行监听消息:

Task<Message> ts = Task.Factory.FromAsync<Message>
    (queue.BeginReceive(), queue.EndReceive);
ts.Wait();

问题是,当调用 Stop() 方法并且没有消息进入 MSMQ 时,所有线程都坐在那里等待消息。我尝试过使用超时,但这种方法对我来说似乎并不优雅(并且已经切换到任务工厂,我不确定目前如何实现它们)。我对此的解决方案是将每个线程的引用添加到数组中,以便我可以取消它们。以下是每个工作线程创建后调用的。

threads[threadId] = Thread.CurrentThread;

然后应该被中止

public void Stop()
{
    try
    {
        this.listen = false;
        foreach(Thread a in threads) {
            a.Abort();
        }
    }
    catch
    {...}
}

关于为什么这不会关闭线程的任何建议?(或者更好的是,谁能告诉我应该在哪里寻找如何正确取消 ts.Wait() ?)

4

1 回答 1

5

使用ManualResetEvent该类来实现正确且优雅地停止正在运行的线程。

另外,不要使用ThreadPool长时间运行的线程,使用你自己创建的线程,否则,有很多长时间运行的任务,你最终可能会出现线程池饥饿,甚至可能导致死锁:

public class MsmqListener
{
    privatec ManualResetEvent _stopRequested = new ManualResetEvent(false);
    private List<Thread> _listenerThreads;
    private object _locker = new _locker();

    //-----------------------------------------------------------------------------------------------------

    public MsmqListener
    {
        CreateListenerThreads();
    }

    //-----------------------------------------------------------------------------------------------------

    public void Start()
    {
      StartListenerThreads();
    }

    //-----------------------------------------------------------------------------------------------------

    public void Stop()
    {
        try
        {
            _stopRequested.Set();
            foreach(Thread thread in _listenerThreads)
            {
                thread.Join(); // Wait for all threads to complete gracefully
            }
        }
        catch( Exception ex)
        {...}
    }

    //-----------------------------------------------------------------------------------------------------

    private void StartListening()
    {
            while( !_stopRequested.WaitOne(0) ) // Blocks the current thread for 0 ms until the current WaitHandle receives a signal
            {
                lock( _locker )
                {
                    postReq = GettingAMessage();
                }
            ...
    }

    //-----------------------------------------------------------------------------------------------------

    private void CreateListenerThreads()
    {
        _listenerThreads = new List<Thread>();
        for (int i = 0; i < Constants.ThreadMaxCount; i++)
        {
            listenerThread = new Thread(StartListening);
            listenerThreads.Add(listenerThread);
        }
    }

    //-----------------------------------------------------------------------------------------------------

    private void StartListenerThreads()
    {
        foreach(var thread in _listenerThreads)
        {
            thread.Start();
        }
    }
}

更新: 我更改了AutoResetEventwith的使用ManualResetEvent以支持停止多个等待线程(使用ManualResetEvent,一旦你发出信号,所有等待线程将被通知并可以自由地继续他们的工作 - 在你的情况下停止消息池)。

使用 volatilebool并不能提供所有保证。它可能仍会读取过时的数据。最好使用底层操作系统同步机制,因为它提供了更强大的保证。来源:stackoverflow.com/a/11953661/952310

于 2014-11-10T16:59:36.513 回答