I am developing a WPF app in C# where I have an Uri that I want to download Json data. The code will deserialize the downloaded Json data to object, thereafter, the object has a list of Uris that would require to request more Json data which i would like to request in parallel. And the downloaded Json data might have more Uris to request. The code should be able to do WebClient.CancelAsync on the parent and its children’s WebClient when desired. I am looking at the Task Parallel Library and finding it difficult to grasp and implement it. I’m unsure if I should use the TPL’s Cancellation token to invoke the CancelAsync or the CancelAsync to cancel the TPL’s Cancellation token. And I not sure if i should use nested Tasks for the children WebClient….?
If anyone has a similar scenario and implemented it using the new TPL.. would you mind sharing a snippet of the code…
Thanks.
If I can suggest using Reactive Extensions (Rx) on top of the TPL then this can be done quite easily without the need for cancellation tasks etc.
If I can assume you have the following:
Then, using Rx, you turn these functions into functions that return observables using the Task Pool, like so:
You’ll need a callback to get the Uri/JSON pairs out. Something like this:
Here’s the recursive LINQ query that will recursively fetch each JSON string:
Then you invoke all of this goodness using the following line:
Now, if you want to cancel the query execution just call this:
Rx handles all of the tasks and cancels them all for you.
I hope this helps.
Here are the links for Rx: