.net async await, what I am doing wrong

Trying to understand use async await to done some work and something just doesn't work. have a code:

private async Task<string> getStringAsync()
{
    var tsk = await Task.Run<string>(() =>
     {
         Task.Delay(2000);
         return "helloWorld";
     });
    return tsk;
}

    private void button2_Click(object sender, EventArgs e)
    {
        tbLog.Text += getStringAsync().Result;
    }

the problem is that getStringAsync().Result never returns anything. though according to documentation it should:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/await

What I am doing wrong?

Jon Skeet
people
quotationmark

You're using Result, which blocks until the task completes. You're using that from the UI thread. So the UI thread will be blocked until the task completes.

Now, that task comes from getStringAsync, which uses await (something). As the "something" in this case won't have completed by the time it's awaited (because it's a two second delay), you're saying "Call me back when that's finished." But because you're just using await (with no ConfigureAwait(false)), you're saying "call me back on the UI thread".

So you end up with a deadlock: the UI thread is waiting for the getStringAsync() task to complete, but that task can't complete until its callback has been executed on the UI thread.

Note that your tsk variable isn't a task as one might expect from the name - it's a string, because you're awaiting the Task<string>.

The simplest solution is not to use Result at all. Instead, make your event handler async and use await from that too:

private async Task<string> GetStringAsync()
{
    var text = await Task.Run(() =>
    {
        Task.Delay(2000);
        return "helloWorld";
    });
    return text;
}

private async void HandleButton2Click(object sender, EventArgs e)
{
    tbLog.Text += await GetStringAsync();
}

people

See more on this question at Stackoverflow