What is the right way to tell a thread that runs a loop to break out of a loop and do something else?

The following code has the disadvantage that the worker thread will not be immediately terminated and will not take the final action after the main thread has reset waithandle. Instead, it will continue to do what it does until it reaches the next iteration of the loop, after which it will be locked indefinitely.

static void Main()
{
 ManualResetEvent m = new ManualResetEvent(true); // or bool b = true
 Thread thread = new Thread(new ThreadStart(delegate()
 {
    while(m.WaitOne()) //or while(b)
    {
        //do something
    }
    //perform final operation and exit
 }));

 thread.Start();

 //do something

 m.Reset(); //or b = false

 //do something else
 }

The following code has the disadvantage that it uses the Abort () method (there are people who say that it should be avoided at all costs), but it does exactly what I am looking for: make the workflow break out of the loop as soon as the main thread tells it to do this, perform the final operation and exit.

static void Main()
{
 Thread thread = new Thread(new ThreadStart(delegate()
 {
    try
    {
        while(true)
        {
            //do something
        }
    }
    catch(ThreadAbortException e)
    {
           //perform final operation and exit
    }
 }));

 thread.Start();

 //do something

 thread.Abort();    

 //do something else
 }

, , ?

( , .net 4.5)

+5
2

BackgroundWorker

static void Main()
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    worker.RunWorkerAsync();

    // do something 

    worker.CancelAsync();

    // do something else
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    while(!worker.CancellationPending)
    {
        // do something
    }
    // perform final action
}

( )

+1

.NET 4.5 ( ), . :

static void Main()
{
    volatile bool keepGoing = true;

    Thread thread = new Thread(new ThreadStart(delegate()
    {
        while(keepGoing)
        {
            //do something
        }

        //logic to perform when the thread is cancelled
    }));

    thread.Start();

    //do something

    keepGoing = false; 

    //do something else
 }

bool volatile, . , , , "" .

http://msdn.microsoft.com/en-us/library/x13ttww7%28VS.80%29.aspx

+1
source

All Articles