我正在使用异步方法。如何在Timer引发超时事件时停止执行?如何停止c#中的异步方法执行?
我的代码:
public async Task<object> Method()
{
cts = new CancellationTokenSource();
try
{
timer = new System.Timers.Timer(3000);
timer.Start();
timer.Elapsed += (sender, e) =>
{
try
{
timer_Elapsed(sender, e, cts.Token, thread);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
return;
}
};
await methodAsync(cts.Token);
return "message";
}
catch (OperationCanceledException)
{
return "cancelled";
}
catch (Exception ex)
{
return ex.Message;
}
}
// Async Call
public async Task<object> methodAsync(CancellationToken ct)
{
try
{
pdfDocument = htmlConverter.Convert("path", "");
}
catch(Exception ex)
{
return x.Message;
}
}
// Timer event
void timer_Elapsed(object sender, ElapsedEventArgs e, CancellationToken ct)
{
cts.Cancel();
ct.ThrowIfCancellationRequested();
}
您似乎试图取消代码'htmlConverter.Convert(“path”,“”)''。无法取消此代码,因为取消代码必须能够响应取消令牌。所以唯一的答案是,如果你需要取消,你需要启动一个新的进程并杀死它。否则唯一安全的行为是让这段代码运行完成。 – Enigmativity
我不想取消这个'pdfDocument = htmlConverter.Convert(“path”,“”);'code。 只要尝试杀死methodAsync()函数。 有什么办法吗? –
'methodAsync'函数中唯一发生的事情就是调用'.Convert',所以停止一个和停止另一个是一样的。您无法安全地强制任务/线程取消。您必须能够响应取消令牌才能正常工作。 – Enigmativity