Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Abort stop all threads or just current. Smart to use Abort?

    RulyCanceler canceler = new RulyCanceler();
    Thread workerThread = new Thread(() =>
    {
        try { Work(canceler, crawler, propertyBag); }
        catch (OperationCanceledException e)
        {
            LogError.WriteError("Working thread canceled!" + Environment.NewLine);
            LogError.WriteError(e);
        }
        catch (Exception e)
        {
            LogError.WriteError(e);
        }
    });
    workerThread.Start();

    bool finished = workerThread.Join(120000);
    if (!finished)
    {
        LogError.WriteError("Aborting thread");
        workerThread.Abort();
    }

I can not figure out if my program stop all threads when Abort is calling or just current thread and program still executing. Sometime program stop unexepected but i do not know if abort is guilty. Can someone tell me?

EDIT:

I modify class like John suggest

class RulyCanceler
    {    
        readonly object _cancelLocker = new object();
        bool _cancelRequest;

        private bool IsCancellationRequested
        {
            get { lock (_cancelLocker) return _cancelRequest; }
        }

        public void Cancel() { lock (_cancelLocker) _cancelRequest = true; }

        public void ThrowIfCancellationRequested()
        {
            if (IsCancellationRequested) throw new OperationCanceledException();
        }
    }

class Test
{
  static void Main()
  {
    var canceler = new RulyCanceler();
    new Thread (() => {
                        try { Work (canceler); }
                        catch (OperationCanceledException)
                        {
                          Console. WriteLine ("Canceled! ");
                        }
                      }). Start();
    Thread. Sleep (1000);
    canceler. Cancel();               // Safely cancel worker.
  }
  static void Work (RulyCanceler c)
  {
    while (true)
    {
      c. ThrowIfCancellationRequested();
      // . . .
      try      { OtherMethod (c); }
      finally  { /* any required cleanup */ }
    }
  }
like image 246
senzacionale Avatar asked Dec 09 '25 22:12

senzacionale


1 Answers

Thread.Abort will only abort the thread which you call it on. However, it's a really bad way of terminating a thread - you should do it in a more controlled and cooperative way. Thread.Abort is a safe way of aborting the currently executing thread, but otherwise you don't know that the thread is at a suitable place to abort without leaving the application in an inconsistent state. You should usually reserve it for times when your whole application is going down anyway.

like image 185
Jon Skeet Avatar answered Dec 11 '25 11:12

Jon Skeet