Posts Tagged ‘asynchronous’
The discussion on using BackgroundWorker here is good but I had to abandon the use of the WebClient class inside the upload object.
Doing async with the BackgroundWorker class (System.ComponentModel) is easy, but when I realized that async could also be done with the WebClient class (System.net) while the BackgroundWorker is executing I had to give it a try so that I could support cancelation. It works, but you have to follow the BackgroundWorker async pattern carefully.
In my case I created a Delivery class that has the responsibility of setting up the BackgroundWorker, staging ftp execution, and clean up. I have an Upload object that manages the async FTP upload separately . This Upload object is created when Delivery.Execute is called and then passed along to the BackgroundWorker.DoWork event hander, named InitDelivery, for execution. Here’s the code for InitDelivery:
Here is how it works:
1) The Upload object is retrieved from the e.Argument.
2) The Upload object is passed to a local field so that it’s internal async operation can be canceled if need be.
3) The method Upload.ExecuteAsync is called.
4) Next we wait for the ‘while(Upload.IsBusy)’ to compete. But you might ask why I am doing this if I am using an async in the Upload object? Here are the reasons:
- The BackgroundWorker is designed for managing long running, synchronous tasks so we need to mimic that pattern inside the BackgroundWorker.DoWork event handler.
- The Upload.IsBusy state is always set to false when the internal async operation finishes regardless of completion, cancelation, or exception.
- I need to use state from the Upload object in the BackgroundWorker.RunWorkerCompleted event handler.
5) The Upload object is passed to e.Result and the event handler exits.
The BackgroundWorker.RunWorkerCompleted event is wired to DeliveryFinish. Here is the code:
Here is how it works:
1) The Delivery.Error property is set from e.Error and the Upload object is retrieved from e.Result.
2) If the Upload object has an error then it is forwarded to the Delivery.Error property.
3) Perform any logging and clean up as necessary.
4) The Try/Finally block ensures that Delivery.IsFinished is always set to true.
Looks like the ‘Upload.IsBusy’ thread really hammers the processor. To remove that I’ve added a Thread.Sleep call that really dampens things down, and it does keep the transfer working.
That’s it for Part 1. In Part 2 I’ll look at the Upload object and cover a few highlights. Here is the link: