Skip to content

Instantly share code, notes, and snippets.

@ctolkien
Last active January 2, 2016 18:29
Show Gist options
  • Save ctolkien/8344264 to your computer and use it in GitHub Desktop.
Save ctolkien/8344264 to your computer and use it in GitHub Desktop.
Blocking on async tasks in asp.net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace XXX
{
public class AsyncHelper
{
private static readonly TaskFactory _taskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
static AsyncHelper()
{
}
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return
TaskExtensions.Unwrap<TResult>(AsyncHelper._taskFactory.StartNew<Task<TResult>>(func))
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
TaskExtensions.Unwrap(AsyncHelper._taskFactory.StartNew<Task>(func)).GetAwaiter().GetResult();
}
}
}
//usage
//return AsyncHelper.RunSync<T>((Func<Task<T>>) (() => asyncFunc()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment