ThrowIfCancellationRequested, correct call with try catch

Markus Freitag 3,791 Reputation points
2023-07-22T18:56:37.33+00:00

Hello,

I have a task that I want to run in parallel. File monitoring. When I press Cancel, how do I catch it correctly?

if (token.IsCancellationRequested)
{
	token.ThrowIfCancellationRequested();
	Log.Error($"DoCheckFile '{FileNewTask}'  The operation was canceled.");  // never
	return $"{text} cancelled";                                              **// never**
}

I never get there, still need a return value, otherwise the compiler shows errors. How would I have to implement a file monitoring correctly, thereby a start and cancellation must be possible?

public void CancelProcess()
{
	if (MyCancellationTokenSource != null)
		MyCancellationTokenSource.Cancel();
}

public string DoProcess()
{
	MyCancellationTokenSource = new CancellationTokenSource();
	var token = MyCancellationTokenSource.Token;
	token = MyCancellationTokenSource.Token;

	Task<string> taskIn = null;
	try
	{
		taskIn = DoCheckFile(token, "Order file monitoring");
	}
	catch (OperationCanceledException cv)
	{
		Log.Error($"OperationCanceledException Exception = {cv.Message}\n{cv.StackTrace}");
		return cv.Message;
	}
	catch (Exception ex)
	{
		Log.Error($"Exception = {ex.Message}\n{ex.StackTrace}");
		return ex.Message;
	}
	return "Ready Order";
}


//Possibility 1
Task<string> DoCheckFile(CancellationToken token, string text)
{
	return Task.Run(() =>
	{
		while (true)
		{
			Trace.WriteLine($"{text} loop  DoCheckFile");

			if (token.IsCancellationRequested)
			{
				token.ThrowIfCancellationRequested();
				Log.Error($"DoCheckFile '{FileNewTask}'  The operation was canceled.");
				return $"{text} cancelled";
			}

			try
			{
				Thread.Sleep(2000);
				string retTask = GetNewOrder();

				TaskNew = retTask;
				Execute();
			}
			catch (OperationCanceledException)
			{
				Log.Error($"####DoCheckFile '{FileNewTask}'The operation was canceled.");
				throw;
			}
			catch (Exception ex)
			{
				//Log.Error($"####DoCheckFile '{ex.Message}'");
			}
		}
		});
}


//Possibility 2
Task<string> DoCheckFile(CancellationToken token, string text)
{
	return Task.Run(() =>
	{
		while (true)
		{
			Trace.WriteLine($"{text} loop  DoCheckFile");
			try
			{
				if (token.IsCancellationRequested)
				{
					token.ThrowIfCancellationRequested();
					Log.Error($"DoCheckFile '{FileNewTask}'  The operation was canceled.");
					return $"{text} cancelled";
				}

			
				Thread.Sleep(2000);
				string retTask = GetNewOrder();

				TaskNew = retTask;
				Execute();
			}
			catch (OperationCanceledException)
			{
				Log.Error($"####DoCheckFile '{FileNewTask}'The operation was canceled.");
				throw;
			}
			catch (Exception ex)
			{
				//Log.Error($"####DoCheckFile '{ex.Message}'");
			}
		}
		});
}

Why can't I do that? Where is the error? Where is try catch right?

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.
11,288 questions
{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.