Skip to content

Instantly share code, notes, and snippets.

@rwhitmire
Last active November 7, 2017 14:13
Show Gist options
  • Save rwhitmire/03edf4f813404db501d271a56ebd1956 to your computer and use it in GitHub Desktop.
Save rwhitmire/03edf4f813404db501d271a56ebd1956 to your computer and use it in GitHub Desktop.
async in sync
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// this will deadlock:
// var message = GetMessageAsync().Result;
// label1.Text = message;
// this will not deadlock... in most cases. use with caution.
var message = AsyncHelper.RunSync(GetMessageAsync);
label1.Text = message;
}
private static async Task<string> GetMessageAsync()
{
await Task.Delay(200);
return "hello!";
}
}
internal static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new TaskFactory(
CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return _myTaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
_myTaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment