我正在编写一个简单的控制台应用程序,该应用程序应该向不同的外部源发出请求,并从最先回答的响应中返回响应。
我尝试使用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());
}
感谢任何帮助。
答案 0 :(得分:3)
您好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 - 代码清晰,立即启动任务。
答案 1 :(得分:2)
你错过了开始任务。
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"; });