终止任务的正确方法是什么?
What is the proper way for terminating tasks?
有一个关于立即终止任务的正确方法的问题。
例如,我有以下代码:
public async Task<string> DoAsync()
{
var result = await Task.Run(() =>
{
//Some heavy request here in a row (5 seconds per request)
DoHeavyRequest(); // 1
DoHeavyRequest(); // 2
DoHeavyRequest(); // 3
DoHeavyRequest(); // 4
return "success";
});
return results;
}
我怎样才能一下子取消这个任务?例如,我 运行 任务持续 7 秒,我预计只有第一个,可能是第二个 "heavy requests" 会被调用,3-4 根本不会被调用。
提前致谢。
我建议取消:
public async Task<string> DoAsync(CancellationToken token) {
var result = await Task.Run(() => {
//TODO: you may want to pass token to DoHeavyRequest() and cancel there as well
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 1
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 2
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 3
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 4
return "success";
});
return "results";
}
// Let's preserve the current interface - call without cancellation
public async Task<string> DoAsync() {
return await DoAsync(CancellationToken.None);
}
...
// Run, wait up to 7 seconds then cancel
try {
using (CancellationTokenSource cts = new CancellationTokenSource(7000)) {
// Task completed, its result is in the result
string result = await DoAsync(cts.Token);
//TODO: Put relevant code here
}
catch (TaskCanceledException) {
// Task has been cancelled (in this case by timeout)
//TODO: Put relevant code here
}
有一个关于立即终止任务的正确方法的问题。 例如,我有以下代码:
public async Task<string> DoAsync()
{
var result = await Task.Run(() =>
{
//Some heavy request here in a row (5 seconds per request)
DoHeavyRequest(); // 1
DoHeavyRequest(); // 2
DoHeavyRequest(); // 3
DoHeavyRequest(); // 4
return "success";
});
return results;
}
我怎样才能一下子取消这个任务?例如,我 运行 任务持续 7 秒,我预计只有第一个,可能是第二个 "heavy requests" 会被调用,3-4 根本不会被调用。
提前致谢。
我建议取消:
public async Task<string> DoAsync(CancellationToken token) {
var result = await Task.Run(() => {
//TODO: you may want to pass token to DoHeavyRequest() and cancel there as well
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 1
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 2
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 3
token.ThrowIfCancellationRequested();
DoHeavyRequest(); // 4
return "success";
});
return "results";
}
// Let's preserve the current interface - call without cancellation
public async Task<string> DoAsync() {
return await DoAsync(CancellationToken.None);
}
...
// Run, wait up to 7 seconds then cancel
try {
using (CancellationTokenSource cts = new CancellationTokenSource(7000)) {
// Task completed, its result is in the result
string result = await DoAsync(cts.Token);
//TODO: Put relevant code here
}
catch (TaskCanceledException) {
// Task has been cancelled (in this case by timeout)
//TODO: Put relevant code here
}