ThrowIfCancellationRequested, correct call with try catch
Markus Freitag
3,791
Reputation points
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?
Sign in to answer