Example: You want to download several UserData containing in a JSON-String. You can have this scenario when you want to show a list with “all users”.
The scenario requires to have a list of integers, that represents the IDs of all users.
Firstly we need to create a pool that gives back a string and accepts a string as parameter.
// Create a new pool BackgroundTask.BackgroundActionPool<String, String> pool = new BackgroundTask.BackgroundActionPool<string, string>();
After that we need to implement a method that will actually download the data from your website.
private String DownloadJsonString(String url) { WebClient clt = new WebClient(); var strJson = clt.DownloadString(url); return strJson; }
Then we need to go to the IDs list and add the Task to download the JsonString right behind the definition of pool.
const String BaseUserDataUrl = "http://www.mywebsite.com/api/userdata/{0}"; var statusMessage = ""; foreach(var id in IDsList) { statusMessage = String.Format("Downloading userdata for user-id {0}", id); var downloadUserDataPart = pool.Create(DownloadJsonString, String.Format(BaseUserDataUrl, id), statusMessage); pool.Add(downloadUserDataPart); } // foreach end pool.OnDone += DownloadData_DoneOne;
You will see, that i added an event trigger for pool.Done. This method can look like this:
void DownloadData_DoneOne (object sender, BackgroundTask.ActionDoneEventArgs<string> e) { if(!e.IsFailed) { ProcessJsonString(e.Result); } // if end else { var action = e.Action as BackgroundTask.BackgroundAction<String, String>; // TODO: error log action.Exception } }