我正在尝试开始一个计数,然后另一个方法将通过生成1到6秒之间的随机数来停止这个计数。我可以执行计数,但stopper函数没有与我的Count函数异步启动。我希望这两个语句同时sart,所以我在同一个DoAsync方法中放入了两个await语句。但它并不像预期的那样工作,因为随机数是在计数结束时生成的。我需要这一代从倒数开始。。。
输出是这样的:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19在2126毫秒内:计数将停止。。。
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
CancellationTokenSource ctSource = new CancellationTokenSource();
CancellationToken ctToken = ctSource.Token;
Task t1 = DoAsync(ctSource, ctToken);
t1.Wait();
}
private static async Task DoAsync(CancellationTokenSource ctSource, CancellationToken ctoken)
{
if (ctoken.IsCancellationRequested)
return;
await Task.Run(() => Count(ctoken), ctoken);
await Task.Run(() => Stop(ctSource), ctoken);
}
public static void Count(CancellationToken ctoken)
{
for (int i = 0; i < 20; i++)
{
if (ctoken.IsCancellationRequested)
{
Console.WriteLine("stopped at :" + i);
break;
}
else
{
Console.WriteLine(i);
Thread.Sleep(150);
}
}
}
public static void Stop(CancellationTokenSource cSource)
{
Random r = new Random();
int milliseconds = r.Next(1000, 6000);
Console.WriteLine("In" + milliseconds + " milliseconds: " + "count will stop...");
Thread.Sleep(milliseconds);
cSource.Cancel();
}
}
}
您可以为此使用Task.WhenAll()。它接受一个任务数组,并创建一个新任务,该任务将在所有源任务完成时完成。
var taskCount = Task.Run(() => Count(ctoken), ctoken);
var taskStop = Task.Run(() => Stop(ctSource), ctoken);
await Task.WhenAll(new [] { taskCount, taskStop });