gpt4 book ai didi

c# - 从方法提前返回时,async/await 是否有额外的成本?

转载 作者:行者123 更新时间:2023-12-04 02:35:40 24 4
gpt4 key购买 nike

与同步方法相比,async/await 在从该方法提前返回时是否有额外的相关成本?

举这些例子:

public async Task<bool> TryDoSomethingAsync()
{
if ( Is99PercentOfTheCases() )
return false; // does this path...

await DoSomethingAsync();

return true;
}

// versus

public bool TryDoSomething()
{
if ( Is99PercentOfTheCases() )
return false; // ...have the same cost as this path?

DoSomething();

return true;
}

我知道 async/await 有相关的额外成本,因此您需要小心周围的紧密循环 - 参见即 https://www.red-gate.com/simple-talk/dotnet/net-framework/the-overhead-of-asyncawait-in-net-4-5/

但是这个成本是什么时候发生的?

  • 是当您将方法标记为异步时吗?
  • 是需要等待的时候吗?
  • 还是跟Task的返回类型有关?
  • 特别是:为异步方法提早返回时性能是否仍然会受到影响?

最后,最好对具体案例进行剖析,但我对它背后的理论很感兴趣。

最佳答案

TryDoSomethingAsync 中的代码被编译器转换为 IL 代码,或多或少等同于此:

public Task<bool> TryDoSomethingAsync()
{
TryDoSomethingAsyncStateMachine stateMachine = new TryDoSomethingAsyncStateMachine();
stateMachine._this = this;
stateMachine._builder = AsyncTaskMethodBuilder<bool>.Create();
stateMachine._state = -1;
AsyncTaskMethodBuilder<bool> _builder = stateMachine._builder;
_builder.Start(ref stateMachine);
return stateMachine._builder.Task;
}

private sealed class TryDoSomethingAsyncStateMachine : IAsyncStateMachine
{
public int _state;
public AsyncTaskMethodBuilder<bool> _builder;
public UserQuery _this;

private TaskAwaiter _awaiter;

private void MoveNext()
{
int num = _state;
bool result;
try
{
TaskAwaiter awaiter;
if (num == 0)
{
awaiter = _awaiter;
_awaiter = default(TaskAwaiter);
num = (_state = -1);
goto IL_0080;
}
if (!_this.Is99PercentOfTheCases())
{
awaiter = _this.DoSomethingAsync().GetAwaiter();
if (!awaiter.IsCompleted)
{
num = (_state = 0);
_awaiter = awaiter;
TryDoSomethingAsyncStateMachine stateMachine = this;
_builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
return;
}
goto IL_0080;
}
result = false;
goto end_IL_0007;
IL_0080:
awaiter.GetResult();
result = true;
end_IL_0007:;
}
catch (Exception exception)
{
_state = -2;
_builder.SetException(exception);
return;
}
_state = -2;
_builder.SetResult(result);
}

void IAsyncStateMachine.MoveNext()
{
//ILSpy generated this explicit interface implementation from .override directive in MoveNext
this.MoveNext();
}

[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine)
{
}

void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
{
//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
this.SetStateMachine(stateMachine);
}
}

与普通异步方法相比,运行的代码要多得多。

但是,运行 Is99PercentOfTheCases() 的代码仍然相当轻量。它会很快,但不如非异步方法快。

关于c# - 从方法提前返回时,async/await 是否有额外的成本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62002676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com