.NET 4.7.2 website
using System;
using System.Threading.Tasks;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string input = Input.Text;
bool iWantDeadlock = input == "yes";
string key = iWantDeadlock
? GetHashFragmentAsync(input).GetResultSafely()
: Task.Run(() => GetHashFragmentAsync(input)).Result;
Response.Redirect(key);
}
}
private static async Task<string> GetHashFragmentAsync(string key)
{
await Task.Delay(100);
return "#" + HttpUtility.UrlEncode(key);
}
}
public static class TaskExtensions
{
public static T GetResultSafely<T>(this Task<T> task)
{
return Task.Run(() => task).Result;
}
}
I made a very simple page, with a textbox, that puts the input in the hashfragment of the page after submitting it.
I was reading up on Tasks and deadlocks (after I ran into some code from others that was causing one).
The solution seems to be to do this:
Task.Run(() => GetHashFragmentAsync(input)).Result;
So I thought, let's make that an extension for clarity and easy use.
public static class TaskExtensions
{
public static T GetResultSafely<T>(this Task<T> task)
{
return Task.Run(() => task).Result;
}
}
This however causes a deadlock. The code is the same, but works very different. Can someone explain this behaviour?