Is using Thread.Abort() and handling ThreadAbortException in .NET safe practice?

前端 未结 7 1015
执念已碎
执念已碎 2020-12-10 06:26

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

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 07:23

    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.

提交回复
热议问题