看代码
var task1 = stream.ReadAsync(bytes, 0, 4);
var task2 = Task.Delay(3000);
var taskfinal = Task.WaitAny(task1, task2);
if (taskfinal==0)
{
Console.WriteLine($"task1完成");
}
else
{
Console.WriteLine($"TIME OUT>>");
}
区别在于:Task.WaitAny阻塞后返回了一个索引,
改用Task.WhenAny
static async Task ReadAsync(int index,NetworkStream stream)
{
Console.WriteLine($"{index} Begin ReadAsync:");
var bytes = new byte[4];
stream.Write(new byte[] { 0xff, 0x00, 0x0d, });
var task1 = stream.ReadAsync(bytes, 0, 4);
var task2 = Task.Delay(3000);
var taskfinal = await Task.WhenAny(task1, task2);
if (taskfinal ==task1)
{
Console.WriteLine($"task1完成");
}
else
{
Console.WriteLine($"TIME OUT>>");
}
}
还是Task.WhenAny后还是一个Task.你可以进行类似的写法:
Task.WhenAny().ContinueWith,
如果你不使用await马上等待,下面还可以继续执行一些代码,直到碰到await.
var task1 = stream.ReadAsync(bytes, 0, 4);
var task2 = Task.Delay(3000);
var taskfinal = Task.WhenAny(task1, task2);
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"some code here , do nothing");
}
if (await taskfinal ==task1)
{
Console.WriteLine($"task1完成");
}
所以又一个区别是Task.WhenAny是异步的写法。