取消所有异步任务 [英] Cancel all async tasks
问题描述
是否有可能取消所有异步方法,不知道什么是当前正在运行的
Is it possible to cancel all async methods, without knowing what is currently running?
例如我有几个类,可能运行的异步任务:?
For example I have several classes that may run async tasks:
class Class1
{
public async void SomeTask()
{
for (int i = 0; i < 5; i++)
{
// Doing some job
await Task.Delay(2000);
}
}
}
class Class2
{
public async void ContinuouslyTask()
{
for (;;)
{
// Doing some job on background
await Task.Delay(1000);
}
}
}
和我要关掉所有的异步任务,在此之前我会注销:
And I want turn off every async task, before I will logout:
class Program
{
static void Main(string[] args)
{
var p = new Program();
var c1 = new Class1();
var c2 = new Class2();
c1.SomeTask();
c2.ContinuouslyTask();
while (Console.ReadKey().Key != ConsoleKey.Enter) { }
p.Logout();
}
private void Logout()
{
// Cancel all async tasks
// And do logout work
}
}
是否有可能做到这一点,但不保存任务分为查询?
Is it possible to do this, without saving tasks into query?
推荐答案
这基本上是扩大@FrankFajardo答案提供一个具体的例子。
当您在传递的CancellationToken
,你还需要监视它从外部的任何取消请求。它看起来是这样的:
This is basically extending @FrankFajardo answer to provide a concrete example.
When you pass in a CancellationToken
, you also need to monitor it for any cancellation request from the outside. It will look like this:
class Class1
{
public async Task SomeTaskAsync(CancellationToken cancellationToken)
{
for (int i = 0; i < 5; i++)
{
if (cancellationToken.IsCancellationRequested)
break;
// Doing some job
await Task.Delay(2000);
}
}
}
class Class2
{
public async Task ContinuouslyTaskAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
// Doing some job on background
await Task.Delay(1000);
}
}
}
而现在,当你想取消它,您只需 CancellationTokenSource.Cancel()
调用添加到您的代码:
And now when you want to cancel it, you simply add CancellationTokenSource.Cancel()
call to your code:
static void Main(string[] args)
{
var p = new Program();
var c1 = new Class1();
var c2 = new Class2();
var cancellationTokenSource = new CancellationTokenSource();
var someTask = c1.SomeTask(cancellationTokenSource.Token);
var continuousTask = c2.ContinuouslyTask(cancellationTokenSource.Token);
while (Console.ReadKey().Key != ConsoleKey.Enter) { }
cancellationTokenSource.Cancel();
Task.WaitAll(someTask, continuousTask);
p.Logout();
}
请注意我用 Task.WaitAll
不仅是因为这是一个控制台应用程序,其中主
不可能是异步。否则,使用 Task.WhenAll
返回一个awaitable 工作
。
Note I'm using Task.WaitAll
only because this is a console application where Main
can't be async. Otherwise, use Task.WhenAll
which returns an awaitable Task
.
这篇关于取消所有异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!