我对基于任务的编程非常陌生,我试图确定如何返回一个任务并验证它是否已经启动。我得到的代码不是我所期望的。控制台应用程序如下:
public static void Main(string[] args)
{
var mySimple = new Simple();
var cts = new CancellationTokenSource();
var task = mySimple.RunSomethingAsync(cts.Token);
while (task.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Starting...");
Thread.Sleep(100);
}
Console.WriteLine("It is started");
Console.ReadKey();
cts.Cancel();
}
public class Simple
{
public async void RunSomething(CancellationToken token)
{
var count = 0;
while (true)
{
if (token.IsCancellationRequested)
{
break;
}
Console.WriteLine(count++);
await Task.Delay(TimeSpan.FromMilliseconds(1000), token).ContinueWith(task => { });
}
}
public Task RunSomethingAsync(CancellationToken token)
{
return Task.Run(() => this.RunSomething(token));
}
}
产出如下:
Starting...
0
It is started
1
2
3
4
为什么要返回的任务的状态为TaskStatus.RanToCompletion而不是TaskStatus.Running,因为我们看到we循环仍然在执行?我是否检查了将RunSomething任务放到线程池而不是RunSomething任务本身的任务的状态?
发布于 2016-12-07 18:52:35
https://stackoverflow.com/questions/41024528
复制相似问题