Shutting down a multithreaded application

前端 未结 6 1741
谎友^
谎友^ 2020-12-05 09:06

I\'m trying to write a ThreadManager for my C# application. I create several threads:
One thread for my text writer.
One thread that monitors some statistics.
M

6条回答
  •  一整个雨季
    2020-12-05 09:24

    What if AddThread is called while your Shutdown is running?

    When shutdown finishes, the thread waiting in AddThread will add a new thread to the collection. This could lead to hangs in your app.

    Add a bool flag that you ever only set in Shutdown to protect against this.

    bool shouldGoAway = false;
    public void AddThread(Thread t)
    {
        lock (_sync)
        {
            if( ! shouldGoAway )
                _threads.Add(t);
        }
    }
    
    public void Shutdown()
    {
        lock (_sync)
        {
            shouldGoAway = true;
            foreach (Thread t in _threads)
            {
                t.Abort(); // does this also abort threads that are currently blocking?
            }
        }
    

    Also you should not use static members - there is no reason for that as you have your Singleton instance.

    .Abort() does not abort threads that are blocking in unmanaged space. So if you do that you need to use some other mechanism.

提交回复
热议问题