Is there an event like Thread.OnAborting ()?

Environment:

Let's say I have a main application that:

  • Listen to requests to complete tasks,
  • Perform these tasks (which use some resources (in the physical sense)) one by one,
  • Must be able to instantly stop a pending task to allocate resources.

I have two timers:

  • In tick, the timer1application receives new requests and stores them in Queue,
  • At tick, the timer2application rejects the request to complete the task in the new one Thread.

When the user requests to stop all the tasks to free up resources, I plan to just kill the thread executing the current task Thread.Abort().

Problem:

I would like to keep the last configuration when destroying a thread from a thread class.

Question:

Is there a way to detect when a thread is killed, such as an event Thread.OnAborting()?

Or maybe I could catch ThreadAbortExceptionon a method call Thread.Abort()? (if so, I really don't know how to do this, could you give some sample code?)

+1
source share
3 answers

ThreadAbortException . , Thread.Abort , ThreadAbortException , . , , AppDomain ..NET 2.0 , , , , AppDomain . , Thread.Abort.

, , . .

  • Thread.Interrupt
  • , API

.

+5

Leito, , , , . , , , , :

class MyTask
{
    bool bShouldDoWork;

    public event EventHandler Aborted;

    public void DoWork()
    {    
         bShouldDoWork = true;          

         while(bShouldDoWork)
         {
              //Do work.
              //But ensure that the loop condition is checked often enough to
              //allow a quick and graceful termination. 
         }

         if(Aborted != null)
         {
              //Fire event
              Aborted(this, EventArgs.Empty);
         }
    }

    //Call this method from another thread, for example
    //when a button is pressed in your UI etc.
    public void Abort()
    {
         bShouldDoWork = false;
    }
}

, . , .

Please do not use Thread.Abort (). It will only give you a lot of headache.

+1
source

All Articles