gpt4 book ai didi

c# - 如何在 ASP.NET Web API 应用程序中调用另一种异步方法

转载 作者:行者123 更新时间:2023-12-03 03:10:53 26 4
gpt4 key购买 nike

因此,我在 ASP.NET Web API 应用程序中具有以下带有异步方法的程序流:API Controller 调用异步方法(我们称之为 asyncMethod1),该方法需要第二个异步方法方法(我们称之为asyncMethod2)。 API Controller 实际上并不需要知道 asyncMethod1 何时完成,尽管为了向用户提供反馈会更好。另一方面,asyncMethod1 确实需要知道 asyncMethod2 何时完成。

相关代码如下:

public class MyController : ApiController
{
private CustomClass customClass;

public IHttpActionResult WorkMethod(TestObject testObject)
{
Debug.WriteLine("WorkMethod - before calling asyncMethod1");

Task.Run(async () => await this.asyncMethod1(testObject)).Wait(); // ERROR HERE

Debug.WriteLine("WorkMethod - after calling asyncMethod1");

return Ok();
}

private async Task asyncMethod1(TestObject testObject)
{
Debug.WriteLine("asyncMethod1 - before calling asyncMethod2");

Dictionary<string, string> x = await this.asyncMethod2(testObject);

Debug.WriteLine("asyncMethod1 - after calling asyncMethod2");

try
{
using (Task<IList<TestResponse>> testTask = customClass.DoAsyncWork1(x))
{
IList<TestResponse> response = await testTask;

// Do something with response
Debug.WriteLine("Transform 'response'");
}
}
catch (Exception ex)
{
throw new Exception(" Exception ", ex);
}
}

private async Task<Dictionary<string, string>> asyncMethod2(TestObject testObject)
{
try
{
Debug.WriteLine("asyncMethod2 - before calling DoAsyncWork2");

using (Task<IList<SomeData>> workTask = customClass.DoAsyncWork2(testObject.x))
{
IList<SomeData> data = await workTask ;

var output = new Dictionary<string, string>();
output = data.values;

Debug.WriteLine("asyncMethod2 - returning data to caller");

return output;
}
}
catch (Exception ex)
{
throw new Exception(" Exception ", ex);
}
}
}

CustomClass 是我正在使用的自定义 API 中的一个类,其中方法 DoAsyncWork1DoAsyncWork2 都是异步的。

当上面的代码运行时,我在方法 WorkMethodTask.Run(async () => wait this.asyncMethod1(testObject)).Wait() 中收到以下异常;:

"Message":"An error has occurred.","ExceptionMessage":"One or more errors occurred.","ExceptionType":"System.AggregateException","StackTrace":" at
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at MyController.WorkMethod(Test testObject) in MyController.cs:line 9
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

输出如下:

WorkMethod - before calling asyncMethod1
asyncMethod1 - before calling asyncMethod2
asyncMethod2 - before calling DoAsyncWork2
asyncMethod2 - returning data to caller
asyncMethod1 - after calling asyncMethod2

如果在方法 WorkMethod 中我更改此:

Task.Run(async () => await this.asyncMethod1(asyncMethod1)).Wait();

对此:

var task = this.asyncMethod1(asyncMethod1);

Debug.WriteLine("WorkMethod - after calling asyncMethod1");

task.wait();

我没有遇到异常,但程序流程永远不会到达 asyncMethod1 中的点,它不会对从 asyncMethod2 返回的响应进行一些处理。另外,输出如下:

WorkMethod - before calling asyncMethod1
asyncMethod1 - before calling asyncMethod2
asyncMethod2 - before calling DoAsyncWork2
WorkMethod - after calling asyncMethod1

这里有什么问题吗?实现我想要实现的目标的正确方法是什么,即从 API Controller 调用异步方法,然后从第一个异步方法调用第二个异步方法?

最佳答案

您在评论中说:

At some point up the chain, you have to have a non-async method, right?!

答案是否定的。一切都可以是异步的。因此,您可以将此作为您的操作:

public async Tack<IHttpActionResult> WorkMethod(TestObject testObject)
{
Debug.WriteLine("WorkMethod - before calling asyncMethod1");

await this.asyncMethod1(testObject);

Debug.WriteLine("WorkMethod - after calling asyncMethod1");

return Ok();
}

那么这样做会使该方法毫无意义。您可以将 asyncMethod1 设为实际的操作方法。如果你愿意的话。

也就是说,您得到的异常是因为实际上存在异常。但因为您没有等待结果,所以它会作为 AggregateException 抛出,真正的异常位于 InnerExceptions 集合中。一旦您等待任务,您就会看到抛出的真正异常。

关于c# - 如何在 ASP.NET Web API 应用程序中调用另一种异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47774768/

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