Created
May 16, 2018 16:22
-
-
Save leonardochaia/98ce57bcee39c18d88682424a6ffe305 to your computer and use it in GitHub Desktop.
C# MVC Controller with deadlock scenarios using Async/Await
This file contains hidden or 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
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Web.Mvc; | |
namespace Test { | |
public class IndexController : Controller { | |
public async Task<string> AsyncString() | |
{ | |
await Task.Delay(1000); | |
return "TestAsync"; | |
} | |
// Test1: DEADLOCK | |
public ActionResult Test1() | |
{ | |
var task = AsyncString(); | |
task.Wait(); | |
// This line will never be reached | |
string res = task.Result; | |
return View(); | |
} | |
// Test2: DEADLOCK | |
public ActionResult Test2() | |
{ | |
var task = AsyncString(); | |
var result = task.ConfigureAwait(false).GetAwaiter().GetResult() | |
// This line will never be reached | |
return View(); | |
} | |
// Test3: DEADLOCK | |
public ActionResult Test3() | |
{ | |
var task = AsyncString(); | |
string res = AsyncHelper.RunSync(() => task); | |
// This line will never be reached | |
return View(); | |
} | |
// Test4: WORKS | |
public ActionResult Test4() | |
{ | |
// Both works | |
// string res = AsyncHelper.RunSync(AsyncString); | |
string res = AsyncHelper.RunSync(() => AsyncString()); | |
return View(); | |
} | |
} | |
/// <summary> | |
/// Taken from https://github.com/IdentityModel/Thinktecture.IdentityModel/blob/master/source/Owin.ResourceAuthorization.WebApi/AsyncHelper.cs | |
/// </summary> | |
internal static class AsyncHelper | |
{ | |
private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); | |
public static void RunSync(Func<Task> func) | |
{ | |
_myTaskFactory.StartNew<Task>(func).Unwrap().GetAwaiter().GetResult(); | |
} | |
public static TResult RunSync<TResult>(Func<Task<TResult>> func) | |
{ | |
return _myTaskFactory.StartNew<Task<TResult>>(func).Unwrap<TResult>().GetAwaiter().GetResult(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment