How can I implement a timeout for a potentially long running action lambda? I have tried wrapping the action in a Task and then using a cancellation token to enforce the timeout but to no avail.
public void LongRunningTask()
{
ExecuteSafely(() => //do something );
}
private void ExecuteSafely(Action action)
{
try
{
action();
}
catch
{
// just don't crash
}
}
New implementation as per 1st answer:
public void Information<T>(string messageTemplate, T propertyValue)
{
ExecuteSafely(() => _logger.Information(messageTemplate, propertyValue));
}
private void ExecuteSafely(Action action)
{
try
{
var cts = new CancellationTokenSource();
cts.CancelAfter(new TimeSpan(0, 0, 1));
try
{
Task.Run(action, cts.Token).Wait();
}
catch (TaskCanceledException e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
//here you know the task is cancelled due to timeout
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
// just don't crash
}
}
This is only working correctly when I step into Task.Run but not when I step over or let it run. Perhaps there is some closure issue with the lambda being passed into the action?
You should use CancellationTokenSource
void Execute(Action action, TimeSpan timeout)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);
try
{
Task.Run(action, cts.Token).Wait();
}
catch (TaskCanceledException e)
{
//here you know the task is cancelled due to timeout
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.