如何正确等待第一个完成的任务

本文关键字:任务 第一个 何正确 等待 | 更新日期: 2023-09-27 18:28:31

我正在编写一个简单的控制台应用程序,它应该向不同的外部源发出请求,并从最先回答的源返回响应。

我试图使用Task对象来实现这一点(以使代码尽可能简单),但我的程序死锁,永远无法完成执行。现在,我怀疑这是因为我在任务中使用了Result,但我不知道如何在没有Result的情况下使其工作。

public static string GetResultFromAnySource()
{
    var t1 = new Task<string>(() => { Thread.Sleep(500); return "Result from source 1"; });
    var t2 = new Task<string>(() => { Thread.Sleep(100); return "Result from source 2"; });
    var res = Task.WhenAny(t1, t2).Result;
    if (res == t1)
        return "Source 1 was faster. Result: " + t1.Result;
    else if (res == t2)
        return "Source 2 was faster. Result: " + t2.Result;
    throw new ApplicationException("Something went very wrong");
}
static void Main(string[] args)
{
    Console.WriteLine(GetResultFromAnySource());
}

感谢您的帮助。

如何正确等待第一个完成的任务

Hi Andre我用async/await关键字重写了你的程序:

class Program {
public static async Task<string> GetResultFromAnySource() {
  var t1 = Task<string>.Run( () => {  Task.Delay(500).Wait(); return "Result from source 1"; });
  var t2 = Task<string>.Run(() => { Task.Delay(100).Wait(); return "Result from source 2"; });
  var res = await Task.WhenAny(t1, t2);
  if (res == t1)
    return "Source 1 was faster. Result: " + await t1;
  else if (res == t2)
    return "Source 2 was faster. Result: " + await t2;
  throw new ApplicationException("Something went very wrong");
}
static void Main(string[] args) {
  Task.Run(async () => await Out()).Wait();
}
static async Task Out()
{
  var str = await GetResultFromAnySource();
  Console.WriteLine(str);
}

}

建议使用Task.Run-代码很清楚,它会立即启动任务。

您错过了启动任务的机会。

t1.Start();
t2.Start();

或者,使用Task.Run()

var t1 = Task.Run<string>(() => { Thread.Sleep(500); return "Result from source 1"; });
var t2 = Task.Run<string>(() => { Thread.Sleep(100); return "Result from source 2"; });