I am using Multithreading
to approach my problem. I have been using Parallel.Foreach
inside the background worker DoWork
event where long running job has been executing. But, the problem arise when I have to cancel the job. It does not cancel the thread immediately.
BackgroundWorker DoWork event :
private void File_DoWork(object sender, DoWorkEventArgs e)
{
var cts = new CancellationTokenSource();
btnCancel.Click += (cancelSender, cancelEvent) =>
{
bgwFile.CancelAsync();
if (bgwFile.CancellationPending)
{
cts.Cancel();
e.Cancel = true;
}
};
object sync = new object();
List<Response> responses = null;
var parallelOperation = new ParallelOptions
{
MaxDegreeOfParallelism = 3,
CancellationToken = cts.Token
};
Parallel.ForEach(listRequest, parallelOperation, request =>
{
lock (sync)
{
responses = GetQueryResponse(request); // Long running process
parallelOperation.CancellationToken.ThrowIfCancellationRequested();
}
});
e.Result = responses ;
}
Here, the problem is when I have to cancel long running job. Suppose, there is three request which has been loop through parallel.foreach having MaxDegreeOfParallelism = 3
,then it goes for GetQueryResponse(request)
method which is long job, if I cancel the thread using CancellationTokenSource
, then it does not cancel the process immediately. It only cancel after executing 3 request thread.
I would like it to cancel it immediately. Is there any approach to cancel all running thread produced by Parallel.Foreach
immediately and goes to RunWorkerCompleted
event of backgroundworker?