System.Threading.Task does not contain definition

后端 未结 2 1427
闹比i
闹比i 2021-01-05 00:23

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

 public async Task WaitAsynchronouslyAsync()
 {         
     await Task.Delay(10000         


        
相关标签:
2条回答
  • 2021-01-05 00:32

    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.

    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:

    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).

    0 讨论(0)
  • 2021-01-05 00:34

    If I interpret the question correctly, it sounds like you are simply using .NET 4.0; Task.Delay was 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

    0 讨论(0)
提交回复
热议问题