Is using Thread.Abort() and handling ThreadAbortEx

2020-02-05 09:05发布

I need to develop a multithreaded Azure worker role in C# - create multiple threads, feed requests to them, each request might require some very long time to process (not my code - I'll call a COM object to do actual work).

Upon role shutdown I need to gracefully stop processing. How do I do that? Looks like if I just call Thread.Abort() the ThreadAbortException is thrown in the thread and the thread can even use try-catch-finally (or using) to clean up resources. This looks quite reliable.

What bothers me is that my experience is mostly C++ and it's impossible to gracefully abort a thread in an unmanaged application - it will just stop without any further processing and this might leave data in inconsistent state. So I'm kind of paranoid about whether anything like that happens in case I call Thread.Abort() for a busy thread.

Is it safe practice to use Thread.Abort() together with handling ThreadAbortException? What should I be aware of if I do that?

7条回答
迷人小祖宗
2楼-- · 2020-02-05 10:10

As others have mentioned, aborting a thread is probably not a good idea. However, signalling a thread to stop with a bool may not work either, because we have no guarantee that the value of a bool will be synchronized across threads.

It may be better to use an event:

class ThreadManager
{
    private Thread thread = new Thread(new ThreadStart(CallCOMMethod));
    private AutoResetEvent endThread = new AutoResetEvent(false);

    public ThreadManager()
    {
        thread.Start();
    }

    public StopThread()
    {
        endThread.Set();
    }

    private void CallCOMMethod()
    {
        while (!endThread.WaitOne())
        {
           // Call COM method
        }
    } 
}

Since the COM method is long running you may just need to "bite the bullet" and wait for it to complete its current iteration. Is the information computed during the current iteration of value to the user?

If not, one option my be:

  • Have the ThreadManager itself run on a separate thread from the UI which checks for the stop notification from the user relatively often.
  • When the user requests that the long running operation be stopped, the UI thread can immediately return to the user.
  • The ThreadManager waits for the long running COM operation to complete its current iteration, then it throws away the results.
查看更多
登录 后发表回答