Task t = new Task(() => grabber.grab(link));
var x = Task.WhenAny(t, Task.Delay(TimeSpan.FromSeconds(3)));
if (x.Result != null)
{
// error cannot implicitly convert System.Threading.Task.Task to string[]
string[] result = x.Result;
foreach (string item in result)
{
list.Add(item);
}
}
函数grab完全同步并返回一个字符串数组
答案 0 :(得分:1)
您正在检查x
任务的结果,该任务可以与t
相同,也可以与Task.Delay(TimeSpan.FromSeconds(3))
的结果相同(前提是await
它)。您应该能够从t
获得结果:
Task<string[]> t = new Task<string[]>(() => grabber.grab(link));
// ^^^^^^^^ also defining what the t.Result should contain
var x = await Task.WhenAny(t, Task.Delay(TimeSpan.FromSeconds(3)));
if (x == t){ // make sure that Task.WhenAny returned the t Task
{
string[] result = t.Result; // get t's Result, not x
foreach (string item in result)
{
list.Add(item);
}
}
创建了一个可重复的小例子here