Created
March 1, 2016 12:04
-
-
Save cmorgado/86a2ba6e900361a3b86c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// transform any sync code to async | |
/// Nice when your implementing an Interface that is "async" but your implementation is no so async | |
public class AsyncUtils | |
{ | |
public static Task<T> FromResultAsync<T>(T result) | |
{ | |
var tcs = new TaskCompletionSource<T>(); | |
tcs.SetResult(result); | |
return tcs.Task; | |
} | |
private static Task _completedTask; | |
public static Task CompletedTaskAsync() | |
{ | |
return _completedTask ?? InitCompletedTaskAsync(); | |
} | |
private static Task InitCompletedTaskAsync() | |
{ | |
var tcs = new TaskCompletionSource<object>(); | |
tcs.SetResult(null); | |
_completedTask = tcs.Task; | |
return _completedTask; | |
} | |
} |
The FromResultAsync(result)
looks to be the same as just calling Task.FromResult(result)
Also, there's now a static Task.CompletedTask
available, and alternatively, retuning Task.FromResult(0)
will return a pre-completed already allocated task with 0 as result!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/// transform any sync code to async
/// Nice when your implementing an Interface that is "async" but your implementation is no so async