Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows form breaks when calling Task.Result

I have code similar to following inside my Windows form:

private async Task<string> GetGreetingAsync()
{
    return await Task.Run(() => "Hello");
}

private void button1_Click(object sender, EventArgs e)
{
    var x = GetGreetingAsync().Result;
}

Clicking the button causes the entire Windows form to freeze and become unresponsive. No exception is thrown.

Even when I don't use the task .Result directly in the event handler and the whole async marked code is in some class library function, which provides interface without async, the problem still occurs. Unit tests for such class library pass without any problems, but when I call its function from event handler on Windows form, it breaks and does not respond.

Why does this happen? How can I fix it?

like image 889
Tom Pažourek Avatar asked Apr 29 '26 03:04

Tom Pažourek


1 Answers

You are blocking the the UI thread with .Result; (see ConfigureAwait)

private async Task<string> GetGreetingAsync()
{
    return await Task.Run(() => "Hello").ConfigureAwait(false);
}

private void button1_Click(object sender, EventArgs e)
{
    var x = GetGreetingAsync().Result;
}

Or go all the way async

private async Task<string> GetGreetingAsync()
{
    return await Task.Run(() => "Hello");
}

async private void button1_Click(object sender, EventArgs e)
{
    var x = await GetGreetingAsync();
}

Using this version you don't even need to await in GetGreetingAsync

private Task<string> GetGreetingAsync()
{
    return Task.Run(() => "Hello");
}

async private void button1_Click(object sender, EventArgs e)
{
    var x = await GetGreetingAsync();
}
like image 159
L.B Avatar answered May 01 '26 16:05

L.B