Correct way to catch the exception // CancellationTokenSource

Markus Freitag 3,791 Reputation points
2023-05-31T09:31:07.0966667+00:00

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#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.