Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Threading.Task does not contain definition

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

 public async Task<string> WaitAsynchronouslyAsync()
 {         
     await Task.Delay(10000);
     return "Finished";
 }
like image 618
Villapando Cedric Avatar asked Jul 18 '13 07:07

Villapando Cedric


2 Answers

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

like image 130
It'sNotALie. Avatar answered Oct 30 '22 18:10

It'sNotALie.


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

like image 35
Marc Gravell Avatar answered Oct 30 '22 19:10

Marc Gravell