Suppose that there are 5 threads, T1, T2, T3, T4 and T5 and 5 of them are currently running. My requirement is to stop all 4 threads in case any one of the 5 threads has any exceptions. How can this be achieved. I am using c# 4.0
This can be achieved by using CancellationTokens. CancellationTokenSource can be shared between your threads.
Here is an example with Tasks, but you can use Threads\ThreadPool
CancellationTokenSource cts = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
while (1 == 1)
{
Thread.Sleep(1000);
Console.WriteLine("Thread1 in progress...");
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Thread1 exiting...");
break;
}
}
}, cts.Token);
Task.Factory.StartNew(() =>
{
while (1 == 1)
{
Thread.Sleep(1000);
Console.WriteLine("Thread2 in progress...");
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Thread2 exiting...");
break;
}
}
}, cts.Token);
Task.Factory.StartNew(() =>
{
while (1 == 1)
{
Thread.Sleep(1000);
Console.WriteLine("Thread3 in progress...");
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Thread3 exiting...");
break;
}
}
}, cts.Token);
Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
try
{
Console.WriteLine("Thread5 in progress...");
int y = 0;
int x = 1 / y;
}
catch
{
Console.WriteLine("Thread5 requesting cancellation...");
cts.Cancel();
}
}, cts.Token);
and check this link which has quite a few CalcellationTokenSource examples (including shared CancellationCancellationTokenSources):
EDIT: I should probably mention that instead of "breaking" the loop when calcellation is requested, you could just call ThrowIfCancellationRequested method of the Token. The outcome will be different though - the task will not "run to completion", it will be in "Cancelled" state. You need to consider this when adding task continuations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With