Correct way to catch the exception // CancellationTokenSource
Markus Freitag
3,791
Reputation points
Hello, I want to trigger a cancel. (Thread, Task, Timer) What is the correct way to catch the exception. There are so many possibilities. Which way is the best? What's your experience?
void GetDataFromServer(int serverNumber, CancellationToken token)
{
for (int i = 0; i < 10; i++)
{
try
{
if (token.IsCancellationRequested)
{
Trace.WriteLine("Canceled while running.");
token.ThrowIfCancellationRequested();
}
++TestPanel.No;
// Make work
Thread.Sleep(1000);
}
catch (OperationCanceledException)
{
Interlocked.Exchange(ref Process, 0);
Trace.WriteLine("The wait operation was canceled.");
throw;
}
}
StartManualResetEvent.Set();
Interlocked.Exchange(ref Process, 0);
}
Developer technologies | C#
11,579 questions
Sign in to answer