我有调用外部lib同步操作的代码,这可能需要很长时间才能完成。我不能重写这个库,并且没有一种方法来停止操作。有什么解决方案可以在超时后停止这项任务吗?强制取消异步包装同步任务
我已经试过这段代码,但它不起作用,因为我预期。等待直到计算未完成。
我该如何解决这个问题?
private static async Task<ResultData> GetResultAsync(string fileName)
{
var timeoutSource = new CancellationTokenSource(new TimeSpan(0, 5, 0));
try
{
return await Task.Run(() =>
{
var result = ExternLib.Calculate(fileName);
if (result == null)
{
throw new CalculationException(fileName);
}
return result;
},
timeoutSource.Token
).ConfigureAwait(false);
}
catch (AggregateException e)
{
SomeCode(e);
}
catch (OperationCanceledException e)
{
SomeCode2(e);
}
catch (Exception e)
{
SomeCode3(e);
}
return await Task.FromResult<ResultData>(null).ConfigureAwait(false);
}
'return await Task.FromResult(null).ConfigureAwait(false);' - >'return null;' –
@StephenCleary我知道这一点。只有一个例外被捕获时才是这种情况。在正常情况下,try块内的返回值将返回正确的结果。 – Anton