1: public class DownloadManager
2: {
3: /// <summary>
4: /// Enqueues the download.
5: /// </summary>
6: /// <param name="uri">The URI.</param>
7: public void DownloadFile(Uri uri)
8: {
9: DownloadState state = new DownloadState
10: {
11: Operation = AsyncOperationManager.CreateOperation(null),
12: Request = (HttpWebRequest)WebRequest.Create(uri)
13: };
14:
15: state.Request.Method = "GET";
16: state.Request.BeginGetResponse(new AsyncCallback(Download_Completed), state);
17: }
18:
19: /// <summary>
20: /// Download_s the completed.
21: /// </summary>
22: /// <param name="result">The result.</param>
23: private void Download_Completed(IAsyncResult result)
24: {
25: DownloadState state = result.AsyncState as DownloadState;
26:
27: if (state != null)
28: {
29: try
30: {
31: HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(result);
32:
33: if (response.StatusCode == HttpStatusCode.OK)
34: state.Operation.PostOperationCompleted(
35: new SendOrPostCallback(OnDownloadCompleted), response);
36: else if (response.StatusCode == HttpStatusCode.NotFound)
37: state.Operation.PostOperationCompleted(
38: new SendOrPostCallback(OnDownloadFailed), new InvalidOperationException());
39: }
40: catch (Exception ex)
41: {
42: state.Operation.PostOperationCompleted(
43: new SendOrPostCallback(OnDownloadFailed), ex);
44: }
45: }
46: }
47:
48: /* ... omissis ... */
49:
50: private class DownloadState
51: {
52: /// <summary>
53: /// Gets or sets the operation.
54: /// </summary>
55: /// <value>The operation.</value>
56: public AsyncOperation Operation { get; set; }
57: /// <summary>
58: /// Gets or sets the request.
59: /// </summary>
60: /// <value>The request.</value>
61: public HttpWebRequest Request { get; set; }
62: }
63: }