0

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;
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
honoyang
  • 3
  • 1
  • 1
    A key feature of *await* is that the code after it runs on the same thread. So `return 1` is expected to run on the form's main UI thread. But that can't happen, the UI thread is busy, waiting for the async code to complete and stuck in the Result property getter. Undiagnosable deadlock is a standard hazard with any gizmo that makes threading look easy. ConfigureAwait(false) would fix it, for example, now `return 1` can execute on a threadpool thread. But realistically you should of course fix the bug and await the task. – Hans Passant Apr 30 '22 at 20:31
  • Take a look here for a detailed explanation. It's exactly the same deadlock. (WinForms has also a single threaded synchronization context associated to the UI thread) https://stackoverflow.com/questions/70660049/how-do-i-avoid-async-void/70660286#70660286 – Federico Alterio May 01 '22 at 00:42
  • Oh you're right! This is a deadlock status, Thank you ! – honoyang May 01 '22 at 05:08

1 Answers1

1

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)

Caius Jard
  • 72,509
  • 5
  • 49
  • 80