fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8.  
  9. namespace WindowsFormsApplication1
  10. {
  11. public partial class Form1 : Form
  12. {
  13. public Form1()
  14. {
  15. InitializeComponent();
  16. }
  17.  
  18. private static Dictionary<Uri, Image> cache = new Dictionary<Uri, Image>();
  19.  
  20. private static Task<Image> DownloadImageAsync(Uri uri)
  21. {
  22. var tcs = new TaskCompletionSource<Image>();
  23. Image cachedImage;
  24. lock (cache)
  25. {
  26. if (cache.TryGetValue(uri, out cachedImage))
  27. {
  28. tcs.SetResult(cachedImage);
  29. return tcs.Task;
  30. }
  31. }
  32.  
  33. var wc = new WebClient();
  34. wc.DownloadDataCompleted += (s, e) =>
  35. {
  36. if (e.Cancelled)
  37. {
  38. tcs.SetCanceled();
  39. }
  40. else if (e.Error != null)
  41. {
  42. tcs.SetException(e.Error);
  43. }
  44. else
  45. {
  46. Bitmap bmp;
  47. using (var stream = new MemoryStream(e.Result))
  48. {
  49. bmp = new Bitmap(stream);
  50. }
  51.  
  52. lock (cache)
  53. {
  54. if (!cache.ContainsKey(uri))
  55. {
  56. cache.Add(uri, bmp);
  57. }
  58. }
  59. tcs.SetResult(bmp);
  60. }
  61. };
  62.  
  63. wc.DownloadDataAsync(uri);
  64. return tcs.Task;
  65. }
  66.  
  67. private void button1_Click(object sender, EventArgs e)
  68. {
  69. var uri = new Uri("http://hoge/sample.png");
  70. DownloadImageAsync(uri).ContinueWith(t =>
  71. {
  72. pictureBox1.Image = t.Result;
  73. });
  74. }
  75. }
  76. }
  77.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty