问题描述
我需要从我的Web API 2控制器调用外部API,类似这里的要求:
I need to call an external api from my Web API 2 controller, similar to the requirement here:
Calling使用的HttpClient从Web API行动外部HTTP服务
然而,上述解决方案需要添加异步
关键字到我的API方法的GET调用,这样就使我的电话是异步的。我preFER我的API的present客户提供一个同步的方法,但是仍然能够从我自己的调用外部API(并且需要我的API返回前返回)。有没有办法做到这一点?
However, the solution above requires adding the async
keyword to my api method's GET call, thus making my call asynchronous. I prefer to present clients of my API with a synchronous method but still be able to call the external api from my own (and will need that to return before my api returns). Is there a way to do this?
推荐答案
禁止上异步
操作可能是危险的。它伤害了性能,并可能导致死锁(多在)
Blocking on an async
operation could be dangerous. It hurts performance and could lead to deadlocks (more in Should I expose synchronous wrappers for asynchronous methods?)
不过,如果你确定这是你想做的事,这是更好IMO使用 GetAwaiter()调用getResult什么()
:
But if you're sure that's what you want to do, It's better IMO to use GetAwaiter().GetResult()
:
using (HttpClient httpClient = new HttpClient())
{
var response = httpClient.GetAsync(_endpoint).GetAwaiter().GetResult();
var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
// Do stuff...
}
这是同样的它是否是一个工作
或任务< T>
,这是同一个呼叫等待
转化为(虽然等待
任务已完成)和 Task.Result
(或 Task.Wait
)包装在 AggregateException
,而 GetAwaiter()任何异常。调用getResult ()
只抛出了第一个例外
为等待
一样。
It's the same whether it's a Task
or Task<T>
, it's the same call await
translates to (although with await
the task already completed) and Task.Result
(or Task.Wait
) wraps any exceptions in AggregateException
while GetAwaiter().GetResult()
throws only the first Exception
as await
does.
这篇关于从网页API调用同步外部API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!