Skip to content

Instantly share code, notes, and snippets.

@Shazwazza
Created May 9, 2014 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shazwazza/108a17c526e3023a1148 to your computer and use it in GitHub Desktop.
Save Shazwazza/108a17c526e3023a1148 to your computer and use it in GitHub Desktop.
Snippet of System.Threading.Tasks.TaskHelpers used in Web Api formatters to RunSynchronously
internal static Task<TResult> RunSynchronously<TResult>(Func<TResult> func, CancellationToken cancellationToken = default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return Canceled<TResult>();
}
try
{
return FromResult(func());
}
catch (Exception e)
{
return FromError<TResult>(e);
}
}
internal static Task<TResult> FromResult<TResult>(TResult result)
{
TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
tcs.SetResult(result);
return tcs.Task;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment