2

i have a .net web api 2 method where i am trying to have some part of my code do something in a separate thread, however after I call the .Wait() method on the task it never hits the next line. I must be overlooking something, but I can't seem to find it. Here's a very simple version of the issue. The line Ok() never gets hit. Any suggestions?

public IHttpActionResult Get() {

    var attachTask = AttachNewTasksAsync();

    //do something else

    attachTask.Wait();

    return Ok();
}

public async System.Threading.Tasks.Task AttachNewTasksAsync()
{
    await System.Threading.Tasks.Task.Delay(10000);
}
WtFudgE
  • 5,080
  • 7
  • 47
  • 59

1 Answers1

8

Deadlock. Your main thread is waiting for attachTask to finish and attachTask cannot finish, because it is waiting for main thread.

Either add ConfigureAwait(false) to Task.Delay or do it properly and await attachTask

This is how it should be written:

public async Task<IHttpActionResult> Get() {

    var attachTask = AttachNewTasksAsync();

    //do something else

    await attachTask;

    return Ok();
}

How to ensure that deadlock will not happen even if someone waits for it synchronously? Use ConfigureAwait(false).

public async System.Threading.Tasks.Task AttachNewTasksAsync()
{
    await System.Threading.Tasks.Task.Delay(10000).ConfigureAwait(false);
}

There is probably nothing I can write, that isn't already covered by Stephen Cleary's blog, so I will just leave this link here.

FCin
  • 3,804
  • 4
  • 20
  • 49