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 ... ?
}
Yes, sleep is blocking.
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.
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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With