-1

I have the following code:

void ThreadMethod()
{
   Console.WriteLine("Thread..");
}

IAsyncResult actionResult;

Action a = new Action();
Thread t = new Thread(new ThreadStart(ThreadMethod));

actionResult = a.BeginInvoke(ActionCompleted, null);
t.Start();

void ActionCompleted(IAsyncResult ar)
{
   if (ar.IsCompleted)
   {
      Console.WriteLine("Action finished");
      t.Abort();
   }
}

How can I stop the action manually? For example

if (actionShouldBeStopped)
{
   action.Stop(); // and ActionComplete should be run.
}

Another option is to change the Action to Thread, but then how should it look like? How can I implement something like ActionCompleted for Thread?

Thanks, Maestro

maestro
  • 671
  • 1
  • 13
  • 27
  • See [this SO thread: lock and listen to CancellationToken](http://stackoverflow.com/q/7416786/485076) perhaps you'll find something helpful – sll Dec 06 '11 at 10:54

1 Answers1

2

I would switch your implementation from Thread to the BackgroundWorker class, it supports cancellation (i.e. stopping the thread), progress report and has an event for when the thread is done (RunWorkerCompleted event)

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110