Correct way to catch the exception // CancellationTokenSource

Markus Freitag 3,786 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);
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,599 questions
{count} votes