使用不等待的ConfigureAwait()

问题描述 投票:0回答:1

我有一个称为Load的方法,该方法正在从同步方法中调用:

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

我能够通过执行以下操作删除建议消息:

this.LoadAsync().ConfigureAWait(false);

没有await关键字,ConfigureAwait(false)是否仍然有效(方法内部的Task.Run将异步运行?

c# asynchronous async-await task configureawait
1个回答
0
投票

ConfigureAwait方法将只创建一个ConfiguredTaskAwaitable结构,异步/等待流控件将使用该结构来指示任务是否应在当前同步上下文中继续。它抑制了警告,但问题仍然存在。

如果要在继续到“ HelloWorld()”中的下一条指令之前等待“ LoadAsync()”完成,则应使用“ this.LoadAsync()。GetAwaiter()。GetResult()”而不是“ this”。 LoadAsync()”或“ this.LoadAsync()。ConfigureAwait(false)”。那比“ this.LoadAsync()。Wait()”更好,因为任何异常都会被引发,而不是获取AggregateException。但是请注意,该任务可能在与“ HelloWorld()”相同的同步上下文中运行,从而导致死锁。

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

但是,如果希望在“ LoadAsync()”仍在运行时完成“ HelloWorld()”,则可以使用“ Task.Run(async()=>等待this.LoadAsync())”。

public void HelloWorld()
{
    Task.Run(async () => await this.LoadAsync());
}
© www.soinside.com 2019 - 2024. All rights reserved.