I was hoping somebody could shed some light on a seemingly complex problem I am having with async webclient downloads in silverlight. Here are the details of my problem-
Downloading a multi-page XML web request. Moved the webclient code into a helperclass to track each individual request. The helper class is called SyncJobsClass. Source for this class at (http://www.silvergeek.net/silverlight/running-async-tasks-synchronously-events-delegates/)
Have a download button to start task-
void button1_Click(object sender, RoutedEventArgs E)
{
var req = new RequestClass;
req.GetXMLPages();
}
Here is the request class-
Public Class RequestClass
{
readonly SyncJobsClass _syncJobs = new SyncJobsClass();
Public void GetXMLPages()
{
_syncJobs += new SyncJobsElementCompleted;
_syncJobs += new SycJobsWorkCompleted;
var pages = 10
for(var i=0;i<10;i++)
{
//load each request into list in _syncjobs class
var url ="www.blahblahblah.com" + i;
_syncJobs.DownloadFiles(url);
}
//start download of each page in list
_syncJobs.StartDownload();
}
}
So as you can see after this step I have a queue of pages being downloaded asynchronously. As the pages are completed I pass them to a XML Linq formatter then bind the resulting data to my ViewModel.
void SyncJobsElementCompleted(string result)
{
if(result == "error")return;
//send data to XML linq parser and add to observable collection for viewmodel.
App.ViewModel.LoadData(result);
}
The problem is for large downloads if I create a new instance of GetXMLPages() by pressing a download button, the previous download is not completed yet and i get mixed results in the viewmodel. I tried changing the button event to –
void button1_Click(object sender, RoutedEventArgs E)
{
var req = new RequestClass;
//Clear view model before download
App.Viewmodel.List.Clear()
// now get pages
req.GetXMLPages();
}
Well this does not work since the download is still going in a different thread..
Tried a boolen but that will only be valid for that instance of RequestClass, which gets recreated on each button press..
How can I prevent another download from being started before I create a new request? If you need more details let me know.. Any help would be greatly appreciated.
I think the boolean is the correct route to go–I’ve run into a similar situation before and used a boolean to solve my problem. You could try storing the boolean in your App class so its not being re-created every time you create a new
RequestClass.