[英]Executing several async function on one object
I'm curious is it possible to execute function Function1
and function Function2
in C# webapi project like in example below.我很好奇是否可以在 C# webapi 项目中执行 function
Function1
和 function Function2
,如下例所示。
Both of these functions are on the same class and use async
and await
but return different types.这两个函数都在同一个 class 上,并使用
async
和await
但返回不同的类型。
Example code below:下面的示例代码:
[ApiController]
[Route("[controller]")]
public class ClassController : ControllerBase
{
// ...
public async Task<ActionResult<string>> Test()
{
var message = await _myClass.Function1().Function2();
return Ok(message);
}
// ...
}
Declaration of _myClass
looks like below: _myClass
的声明如下所示:
public class MyClass
{
// ...
public async Task<MyClass> Function1()
{
// code which uses `await` below
// ....
// end of this code
return this;
}
public async Task<string> Function2()
{
// code which uses `await` below
// ....
// end of this code
return "some text";
}
}
Yes, you can do this:是的,你可以这样做:
public async Task<ActionResult<string>> Test()
{
var message = await
_myClass.Function1().ContinueWith(resultingMyClass =>
resultingMyClass.Result.Function2());
return Ok(message);
}
But the most obvious solution would be to use the async/await syntax that C# provides:但最明显的解决方案是使用 C# 提供的 async/await 语法:
public async Task<ActionResult<string>> Test()
{
var result1 = await _myClass.Function1();
var message = await result1.Function2();
return Ok(message);
}
If you don't need the result from the first call as input to the second function you can run multiple Tasks in parallel and wait until they have all finished using Task.WhenAll
.如果您不需要第一次调用的结果作为第二个 function 的输入,您可以并行运行多个任务并等待它们全部使用
Task.WhenAll
完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.