Skip to content

Instantly share code, notes, and snippets.

@cmorgado
Created March 1, 2016 12:04
Show Gist options
  • Save cmorgado/86a2ba6e900361a3b86c to your computer and use it in GitHub Desktop.
Save cmorgado/86a2ba6e900361a3b86c to your computer and use it in GitHub Desktop.
/// 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;
}
}
@cmorgado
Copy link
Author

cmorgado commented Mar 1, 2016

/// transform any sync code to async
/// Nice when your implementing an Interface that is "async" but your implementation is no so async

@pedrolamas
Copy link

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