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

Time:05-01

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;
    }

CodePudding user response:

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)

  •  Tags:  
  • c#
  • Related