user2214609
user2214609

Reputation: 4951

Stop my task and all my waiting task

i have an application who take all the added files from my Listbox and play this files:

IEnumerable<string> source

public void play()
{
    Task.Factory.StartNew(() =>
    {
        Parallel.ForEach(source,
                         new ParallelOptions
                         {
                             MaxDegreeOfParallelism = 1 //limit number of parallel threads 
                         },
                         file =>
                         {
                              //each file process via another class
                         });
    }).ContinueWith(
            t =>
            {
                OnFinishPlayEvent();
            }
        , TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
        );
    }

my processing file can be stop via my class property but if i want to stop all the files that waiting how can i do it ?

Upvotes: 0

Views: 122

Answers (2)

Sean H
Sean H

Reputation: 746

If you want to stop a parallel loop, use an instance of the ParallelLoopState class. To cancel a task, you want to use a CancellationToken. Since you are embedding your parallel loop inside a task, you can simply pass a cancellation token into the task. Bear in mind, this will throw an OperationCanceledException you will have to catch, if you choose to wait on your task(s).

For example, and for the sake of argument, we'll assume that something else will call a delegate inside your class that will set the cancellation token.

CancellationTokenSource _tokenSource = new CancellationTokenSource();

//Let's assume this is set as the delegate to some other event
//that requests cancellation of your task
void Cancel(object sender, EventArgs e)
{
  _tokenSource.Cancel();
}

void DoSomething()
{
  var task = Task.Factory.StartNew(() => { 
    // Your code here...
  }, _tokenSource.Token);

  try {
    task.Wait();
  }
  catch (OperationCanceledException) {
    //Carry on, logging that the task was canceled, if you like
  }
  catch (AggregateException ax) {
    //Your task will throw an AggregateException if an unhandled exception is thrown
    //from the worker. You will want to use this block to do whatever exception handling
    //you do.
  }
}

Bear in mind, there are better ways to do this (and I'm typing from memory here, so there could be some syntax errors and the like), but this should get you started.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564433

You need to design your routines to accept a CancellationToken, and then trigger a CancellationTokenSource.Cancel().

This will allow you to provide a mechanism to cooperatively cancel your work.

For details, see Cancellation in Managed Threads and Task Cancellation on MSDN.

Upvotes: 1

Related Questions