本文介绍了如何从任务&LT返回结果; Htt的presponseMessage>中采取异步的利益HttpClient的电话吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写code(1),如波纹管

public Task<HttpResponseMessage> Get(int id)
{
 return Task<HttpResponseMessage>.Factory.StartNew(() =>
  Request.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(model)));

}

我可以写code(第2),如波纹管

public Task<HttpResponseMessage> Put(int id, string value)
{
   return Task<HttpResponseMessage>.Factory.StartNew(() =>
     Request.CreateResponse(HttpStatusCode.OK));

}

我要打电话上述的使用方法 Httpclient.PutAsJsonAsync()。在.NET 4.0中?

I want call above described Put method using Httpclient.PutAsJsonAsync(). in .Net 4.0 ?

或者有什么更好的方法来做到这一点?所以,我可以采取异步调用的好处?

Or any better way to do that ? So I can take the benefit of Async call ?

推荐答案

如果没有在code中的操作都是异步的(或阻塞),那么就没有意义有一个异步操作。在你有两个例子,操作只返回一个响应,这样你就不会需要使用任务&LT; Htt的presponseMessage&GT; 响应,使用的Htt presponseMessage 就好了。

If none of the operations in your code are asynchronous (or blocking), then it does not make sense to have an asynchronous operation. In the two examples you have, the operation just returns a response, so you don't need to use a Task<HttpResponseMessage> response, using the HttpResponseMessage is just fine.

所以,更直接您的问题,是的,你可以写code这样的,但它比必要的更复杂,会造成不必要的上下文切换(创建新任务),并且是整体不太高性能。你可以这样做,但你不应该。

So, more direct to your question, yes, you can write code like that, but it's more complicated than necessary, will cause a needless context switch (to create the new task), and is overall less performant. You can do it, but you shouldn't.

这篇关于如何从任务&LT返回结果; Htt的presponseMessage&gt;中采取异步的利益HttpClient的电话吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:17