LeoQns
LeoQns

Reputation: 1332

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

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 ?

Upvotes: 0

Views: 12438

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87258

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.

Upvotes: 3

Related Questions