开发者

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

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(){ callba开发者_如何学Cck(message); }, 1000);
}

C#-5.0:

public static async Task<string> ReturnItAsync(string it) {
    //return await ... ?
}


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);
}


When I need to mimic the JavaScript's setTimeout(callback, milliseconds) function I use the code below:

Scheduling work to thread pool (fire-and-forget non-blocking scheduling):

Task.Run(() => Task
            .Delay(TimeSpan.FromSeconds(1))
            .ContinueWith(_ => callback(message)));

There are variations of this when one can provide a cancellation token to cancel the task before the delay has elapsed. Unless I misunderstood, the selected answer by Ilian Pinzon is more suited for an awaited situation, which in case of fire-and-forget (JavaScript) isn't what you wanted.

Note: the TimeSpan.FromSeconds(1) is for convenience, if milliseconds are desired the whole TimeSpan can be eschewed in favor of a millisecond value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜