How to return result from Task <HttpResponseMessage> to take advantage of Async HttpClient call?
Can I write the code (1st), for example, below,
public Task<HttpResponseMessage> Get(int id) { return Task<HttpResponseMessage>.Factory.StartNew(() => Request.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(model))); } Can I write the code (2nd) as shown below.
public Task<HttpResponseMessage> Put(int id, string value) { return Task<HttpResponseMessage>.Factory.StartNew(() => Request.CreateResponse(HttpStatusCode.OK)); } I need a call to the Put method described above using Httpclient.PutAsJsonAsync() . in .Net 4.0?
Or is there any better way to do this? So can I use asynchronous call?
If none of the operations in your code is asynchronous (or blocking), then it makes no sense to have an asynchronous operation. In the two examples that you have, the operation simply returns a response, so you do not need to use the Task<HttpResponseMessage> response using HttpResponseMessage . This is normal.
So, more directly to your question, yes, you can write such code, but it is more complicated than necessary, it will cause an unnecessary context switch (to create a new task) and generally less effective. You can do it, but you shouldn't.