Michael
Michael

Reputation: 1605

Task.Wait Deadlocks on a Task returned by Task.Run

I'm having a deadlock issue with some async code in 4.5. I read Stephen Cleary's blog about preventing deadlocks that occur when the task captures the executing context then in that same context you block by waiting for the Task. I tried to implement the solution but I'm still getting deadlocks and I'm not seeing why.

Original Code

Consuming Class:

private void Update(...)
    {
        //... do some stuff ... 
        _repository.Save(listing).Wait();
    }

Class that returns the Task:

protected override Task Save(...)
    {
        return Task.Run(() =>
        {
            ... do some stuff ...
            _logger.Debug("All Done!!!");
        });
    }

Modified Code

Consuming Class:

private void Update(...)
    {
        //... do some stuff ... 
        _repository.Save(listing).Wait();
    }

Class that returns the Task:

protected override async Task Save(...)
    {
        await Task.Run(() =>
        {
            ... do some stuff ...
            _logger.Debug("All Done!!!");
        }).ConfigureAwait(false);
    }

Even in the modified version, where I am explicitly telling the awaitable Task not to bind to the context, I still get a deadlock.

Any ideas what might be going on?

Upvotes: 1

Views: 1557

Answers (1)

user2707115
user2707115

Reputation:

Try the normal async await pattern

private async void Update(...)
{
    //... do some stuff ... 
   await _repository.Save(listing);
}

protected override async Task Save(...)
{

        ... do some stuff ...
        _logger.Debug("All Done!!!");
}

Upvotes: 2

Related Questions