, , , , WebClient?
, , .NET , . , , Stream, BeginRead EndRead. IAsyncResult , , . ( MSDN)
async , , WebClient, DownloadString/DownloadStringAsync DownloadStringCompleted. , , , , Begin/End.
, . , , . Download/DownloadAsync, DownloadCompleted, .
Here is a very simple implementation. Note that the only method that really does any work is a single synchronous boot method. It is also important to note that this is not the most efficient way to do this. If you want to take advantage of the async IO HttpWebRequest and the like, this example will quickly get complicated. There's also an overly complex Async Operation that I never liked a single bit.
class Downloader {
public void Download(string url, string localPath) {
if (localPath == null) {
localPath = Environment.CurrentDirectory;
}
}
public void Download(string url) {
Download(url, null);
}
public void DownloadAsync(string url, string localPath) {
ThreadPool.QueueUserWorkItem( state => {
Download(url, localPath);
SynchronizationContext.Current.Post( OnDownloadCompleted, null );
});
}
public void DownloadAsync(string url) {
DownloadAsync(url, null);
}
private void OnDownloadCompleted(object state) {
var handler = DownloadCompleted;
if (handler != null) {
handler(this, EventArgs.Empty);
}
}
public event EventHandler DownloadCompleted;
}
source
share