I'm having a bit of trouble structuring a class library for uploading files (via HTTP/FTP)and asynchronously reporting their progress. My first pass at code looks something like this:
WebClient wc = new WebClient();
// setup credentials, etc
...
// install callbacks
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(myProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(myFileCompleted);
foreach ( file to send )
{
wait = new System.Threading.AutoResetEvent(false);
// send file, block until done.
wc.UploadFileAsync(URI, null, {file name}, wait);
wait.WaitOne();
}
This is running on the main UI thread. The Progress callback updates a window of status information. The Completed callback sets the "wait" event object, to release the block following the asynch send.
The problem is that the entire code blocks on the WaitOne call -- the Progress() and Completed() callbacks never get called (even though the file is succesfully sent ok). I would have that these callbacks would be issued on the thread processing the async send, but apparently this isn't so. (even though MS's documentation for the event:
http://msdn.microsoft.com/en-us/library/system.net.uploadfilecompletedeventhandler.aspxuses just such a model).
If I remove the WaitOne call, everything works fine -- for one single file. But without synchronizing, multiple sends are dispatched simultaneously. This could be worked around by unrolling the foreach loop into the Completed() handler to simulate synchronous operation, but that seems a bit messy. Is there a better solution other than spawning this all off onto its own thread?
Thanks in advance,
masher