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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
FromResultAsync(result)
looks to be the same as just callingTask.FromResult(result)
Also, there's now a static
Task.CompletedTask
available, and alternatively, retuningTask.FromResult(0)
will return a pre-completed already allocated task with 0 as result!