0

I have a method called Load which is being invoked from a synchronous method:

private async Task LoadAsync()
{
  await Task.Run(() => // stuff....).ConfigureAwait(false);
}

public void HelloWorld()
{
  this.LoadAsync(); // this gives me a suggestion/message, "because this call is not awaited,.... consider using await.
}

I was able to remove the suggestion message by doing this:

this.LoadAsync().ConfigureAWait(false);

Does the ConfigureAwait(false) still work (the Task.Run inside the method will run asychronously) without the await keyword?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
AlvinfromDiaspar
  • 6,611
  • 13
  • 75
  • 140
  • 2
    In your view, what would it mean for `ConfigureAwait(false)` to "work"? Its behavior is right there in the method name: `Configure` **`Await`** `(false)`. You seem to be using the method as a hack to avoid the warning about not awaiting the awaitable. Don't put hacks in your code. Do things the right way. See proposed duplicate for advice about that. – Peter Duniho Jan 25 '20 at 00:54

1 Answers1

3

The ConfigureAwait method will just create a ConfiguredTaskAwaitable struct, that is used by the async/await flow control to indicate if the task should or should not continue in the current synchonization context. It suppress the warning, but the problem still exist.

If you want to wait for "LoadAsync()" to finish before proceeding to next instruction inside "HelloWorld()", you should use "this.LoadAsync().GetAwaiter().GetResult()" instead of "this.LoadAsync()" or "this.LoadAsync().ConfigureAwait(false)". That is better than "this.LoadAsync().Wait()" because any exception will be received as thrown, instead of getting an AggregateException. But be aware that the task could run in the same synchronization context of "HelloWorld()", causing a deadlock.

public void HelloWorld()
{
    this.LoadAsync().GetAwaiter().GetResult();
}

But if you want "HelloWorld()" to finish while "LoadAsync()" is still running, you may use "Task.Run(async () => await this.LoadAsync())".

public void HelloWorld()
{
    Task.Run(async () => await this.LoadAsync());
}