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
Should I use
TaskEx.Run
to runNewtonsoft.Json.JsonConvert.DeserializeObject
?
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
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
.