如何在c#中使用带有out参数的异步等待

KC *_*C P -1 c# asynchronous async-await

我们如何在没有 out 参数的 C# 中安全地使用 async-await。

例如

async public void someMethod(){
     await someOtherMethod (out string outputFromSomeOtherMethod);
     .......
     .....

} 
Run Code Online (Sandbox Code Playgroud)

AAA*_*ddd 5

简而言之,您不(并且您不能),我们使用 return

此外,当你考虑它时,它没有任何意义,它是一个在它喜欢的时候完成的任务,如果你能做到,你会强迫它等待 out 参数

public async Task<SomeResult> someOtherMethod() { .. }

...

var myAwesomeResult = await someOtherMethod();
Run Code Online (Sandbox Code Playgroud)

此外,您冷使用 a delegatefunc<T,U>Action<T>作为参数

public async Task someOtherMethod(Action<bool> someResult)
{
   await somestuff;
   someResult(true);
}

...

await someOtherMethod(b => YayDoSomethingElse(b));
Run Code Online (Sandbox Code Playgroud)

Ooor 正如Daniel A. White评论的那样,ValueTuple如果您需要轻松访问多种返回类型,则可以返回 a

public async Task<(int someValue,string someOtherValue)> someOtherMethod() {.. }
Run Code Online (Sandbox Code Playgroud)

  • 您还可以返回一个可能有意义的元组。 (2认同)