0

I have a parallel foreach loop running within an event on a asp.net web page. How can I cancel it using cancellation token?This can be a very long operation - and what is bothering me is - it seems to be posting back while the operation is running - so how can I trigger another event to use the cancellation token? Is this possible?

protected void btnSend_Click(object sender, EventArgs e)
{
    mailList = tbEmailTo.Text.Split(
        new string[] { "," }, 
        StringSplitOptions.RemoveEmptyEntries).ToList();
    Parallel.ForEach(emailList, email =>
    {   
        //just sending email  
    });
}
juharr
  • 31,741
  • 4
  • 58
  • 93

2 Answers2

1

Pass to you Parallel.ForEach CancellationToken and check inside of your loop if cancellation is requested. If it's requested it will throw exception and exit your loop. Calling

cts.Cancel();

from outside of your loop will set CancellationToken to Cancel state and it will throw exception inside of your Parallel.ForEach loop.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;

try
{
    Parallel.ForEach(emailList, po, (email) =>
    {
        //just sending email here

        po.CancellationToken.ThrowIfCancellationRequested();
    });
}
catch (OperationCanceledException e)
{
}
finally
{
    cts.Dispose();
}
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
0

Well it definitely won't cancel the send portion of your parallel loop as that code doesn't know or understand about your cancellation token. If you need the ability to stop immediately rather than a graceful cancel, then you should consider coding up your own threads so that you can kill the entire thread. Or at least use a different library that runs your code in it own thread, something like a private thread pool perhaps.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57