honoyang
honoyang

Reputation: 7

C# winform: what's wrong in this async example if access result before await

Here's my test code. With this code, my form will get stuck after executing task.Result (it's a "not yet computed" status).

I know this is bad programming style - but I'm curious what happened about this task.Result status.

Thanks.

    private async Task<int> func()
    {
        await Task.Run(() =>
        {
            ;
        });

        return 1;
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        Task<int> task = func();     

        if (task.Result > 1)
        { ; }

        await task;
    }

Upvotes: 0

Views: 163

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

From the documentation of Task.Result:

Remarks

Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

By the time you await the task (which wouldn't jam your form) the task is already completed thanks to accessing .Result (which will jam your form)

Upvotes: 1

Related Questions