Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nonblocking sleep in C#5.0 (like setTimeout in JavaScript)

Tags:

c#

c#-5.0

What is the analog of JavaScript's setTimeout(callback, milliseconds) for the C# in a new "async" style?

For example, how to rewrite the following continuation-passing-style JavaScript into modern async-enabled C#?

JavaScript:

function ReturnItAsync(message, callback) {
    setTimeout(function(){ callback(message); }, 1000);
}

C#-5.0:

public static async Task<string> ReturnItAsync(string it) {
    //return await ... ?
}
like image 575
Artazor Avatar asked Oct 02 '11 22:10

Artazor


People also ask

Is Sleep blocking in C?

Yes, sleep is blocking.

Is Sleep blocking the thread?

Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.

How do you make wait not blocking?

wait() is always blocking. waitpid() can be used for blocking or non-blocking. we can use waitpid() as a non-blocking system call with the following format: int pid = waitpid(child_pid, &status, WNOHANG);


1 Answers

AsyncCTP has TaskEx.Delay. This wraps timers in your task. Note, that this is not production-ready code. TaskEx will be merged into Task when C# 5 arrives.

private static async Task ReturnItAsync(string it, Action<string> callback)
{
    await TaskEx.Delay(1000);
    callback(it);
}

Or if you want to return it:

private static async Task<string> ReturnItAsync(string it, Func<string, string> callback)
{
    await TaskEx.Delay(1000);
    return callback(it);
}
like image 125
Ilian Avatar answered Oct 09 '22 12:10

Ilian