Good evening,
I am trying to refine some code using async programming and would like to know if the following code is well written or not, and if is there any way to imp
I am using following code in production without any issues.
// Creating and disposing HttpClient is unnecessary
// if you are going to use it multiple time
// reusing HttpClient improves performance !!
// do not worry about memory leak, HttpClient
// is designed to close resources used in single "SendAsync"
// method call
private static HttpClient client;
public Task<T> DownloadAs<T>(string url){
// I know I am firing this on another thread
// to keep UI free from any smallest task like
// preparing httpclient, setting headers
// checking for result or anything..., why do that on
// UI Thread?
// this helps us using excessive logging required for
// debugging and diagnostics
return Task.Run(async ()=> {
// following parses url and makes sure
// it is a valid url
// there is no need for this to be done on
// UI thread
Uri uri = new Uri(url);
HttpRequestMessage request =
new HttpRequestMessage(uri,HttpMethod.Get);
// do some checks, set some headers...
// secrete code !!!
var response = await client.SendAsync(request,
HttpCompletionOption.ReadHeaders);
string content = await response.Content.ReadAsStringAsync();
if(((int)response.StatusCode)>300){
// it is good to receive error text details
// not just reason phrase
throw new InvalidOperationException(response.ReasonPhrase
+ "\r\n" + content);
}
return JsonConvert.DeserializeObject<T>(content);
});
}
ConfigureAwait is tricky, and makes debugging more complicated. This code will run without any issues.
If you want to use CancellationToken
then you can pass your token in client.GetAsync
method.
Should I use
TaskEx.Run
to runNewtonsoft.Json.JsonConvert.DeserializeObject<T>
?
Throwing the JSON deserialisation onto another thread likely won't achieve anything. You're freeing up the current thread but then need to wait for your work to be scheduled on another thread. Unless you need Newtonsoft.Json APIs specifically, consider using ReadAsAsync<T>. You can use that with a JsonMediaTypeFormatter, which uses Newtonsoft.Json internally anyway.
Is there any good way (without checking the object properties) to know if rootObject was successfully created?
You need to define what success looks like. For example, your JSON could be null
, so rootObject
is null. Or it could be missing properties, or your JSON has extra properties that were not deserialised. I don't think there's a way to fail the serialisation for excess or missing properties, so you would have to check that yourself. I could be wrong on this point.
Should I check somewhere whether Cancellation was requested or not?
You need to see what makes sense in your code and when it is being cancelled. For example, there's no point acting on the cancellation token as the very last line in your function, when all the work has been completed.
Does it make sense for your application to cancel the operation if the JSON has been downloaded, but not yet deserialised? Does it make sense for your application to cancel the operation if the JSON has been deserialised, but the object graph has not yet been validation (question 2)?
It really depends on your needs, but I'd probably cancel if the download has not yet completed - which it seems that you are already doing - but once the download is completed, that is the point of no return.
What would you change? and why?
Use ConfigureAwait(false)
on the Tasks that you await
. This prevents deadlocks if your code ever blocks and waits for the resulting Task (e.g. .Wait()
or .Result
).
Use using
blocks instead of try
-finally
.