C# System.Threading.Task 不包含定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17717047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:17:29  来源:igfitidea点击:

System.Threading.Task does not contain definition

c#multithreading

提问by Villapando Cedric

I cant have .Delay definition on my System.Threading.Task.

我的 System.Threading.Task 上不能有 .Delay 定义。

 public async Task<string> WaitAsynchronouslyAsync()
 {         
     await Task.Delay(10000);
     return "Finished";
 }

采纳答案by It'sNotALie.

You are using .NET 4. Back then, there was no Task.Delay. However, there was a library by Microsoft called Microsoft.Bcl.Async, and it provides an alternative: TaskEx.Delay.

您使用的是 .NET 4。那时,还没有Task.Delay. 然而,微软有一个名为Microsoft.Bcl.Async的库,它提供了一个替代方案:TaskEx.Delay.

It would be used like this:

它将像这样使用:

public async Task<string> WaitAsynchronouslyAsync()
{         
    await TaskEx.Delay(10000);
    return "Finished";
}

Your other options are to either update to .NET 4.5, or just implement it yourself:

您的其他选择是更新到 .NET 4.5,或者自己实现:

public static Task Delay(double milliseconds)
{
    var tcs = new TaskCompletionSource<bool>();
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Elapsed += (o, e) => tcs.TrySetResult(true);
    timer.Interval = milliseconds;
    timer.AutoReset = false;
    timer.Start();
    return tcs.Task;
}

(taken from Servy's answer here).

(取自Servy的回答here)。

回答by Marc Gravell

If I interpret the question correctly, it sounds like you are simply using .NET 4.0; Task.Delaywas added in .NET 4.5. You can either add your own implementation using something like a system timer callback and a TaskCompletionSource, or: just update to .NET 4.5

如果我正确解释了这个问题,听起来您只是在使用 .NET 4.0;Task.Delay是在 .NET 4.5 中添加的。您可以使用系统计时器回调和TaskCompletionSource, 之类的东西添加自己的实现,或者:只需更新到 .NET 4.5