How to return result from Task<HttpResponseMessage>, to take the benefit of Async HttpClient call?

萝らか妹 提交于 2019-12-23 05:33:07

问题


Can I write code (1st) like bellow

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

}

Can I write code (2nd) like bellow

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

}

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 ?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/15933350/how-to-return-result-from-taskhttpresponsemessage-to-take-the-benefit-of-asyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!