Guest User

Untitled

a guest
Nov 14th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace Parallel
  10. {
  11. public enum Actions
  12. {
  13. TestParallelDownload,
  14. TestParallelSaveFile,
  15. TestAsyncDownload,
  16. TestAsyncSaveFile
  17. }
  18.  
  19. public class Program
  20. {
  21. public static async Task Main(string[] args)
  22. {
  23. try
  24. {
  25. var stopWatch = Stopwatch.StartNew();
  26. var itemAmount = 5;
  27.  
  28. await Test(Actions.TestParallelDownload, itemAmount);
  29. await Test(Actions.TestParallelSaveFile, itemAmount);
  30.  
  31. await Test(Actions.TestAsyncDownload, itemAmount);
  32. await Test(Actions.TestAsyncSaveFile, itemAmount);
  33.  
  34. stopWatch.Stop();
  35. Console.WriteLine("Finish {0}", stopWatch.Elapsed);
  36. Console.ReadLine();
  37. }
  38. catch (Exception ex)
  39. {
  40. Console.WriteLine("Err", ex.Message);
  41. Console.ReadLine();
  42. }
  43. }
  44.  
  45. public static async Task Test(Actions action, int itemAmount)
  46. {
  47. string[] items = Enumerable.Range(0, itemAmount).Select(i => Guid.NewGuid().ToString()).ToArray();
  48. var stopWatch = Stopwatch.StartNew();
  49.  
  50. switch (action)
  51. {
  52. case Actions.TestParallelDownload:
  53. items.AsParallel().ForAll(item => DownloadAsync(item));
  54. break;
  55. case Actions.TestParallelSaveFile:
  56. items.AsParallel().ForAll(item => SaveAsync(item));
  57. break;
  58. case Actions.TestAsyncDownload:
  59. foreach (var item in items)
  60. await DownloadAsync(item);
  61. break;
  62. case Actions.TestAsyncSaveFile:
  63. foreach (var item in items)
  64. await SaveAsync(item);
  65. break;
  66. }
  67.  
  68. stopWatch.Stop();
  69.  
  70. Console.WriteLine($"{action.ToString()} Call: Time: {stopWatch.Elapsed}");
  71. }
  72.  
  73. public static async Task SaveAsync(string textToWrite)
  74. {
  75. string filePath = @"C:tempfile2.txt";
  76. byte[] encodedText = Encoding.Unicode.GetBytes(textToWrite);
  77.  
  78. using (var sourceStream = new FileStream(filePath,
  79. FileMode.Append, FileAccess.Write, FileShare.None,
  80. bufferSize: 4096, useAsync: true))
  81. {
  82. await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
  83. };
  84. }
  85.  
  86. public static async Task DownloadAsync(string name)
  87. {
  88. var uri = new Uri("https://images.sftcdn.net/images/t_app-logo-l,f_auto,dpr_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/2183169552/the-test-fun-for-friends-logo.png");
  89. using (var client = new WebClient())
  90. {
  91. await client.DownloadFileTaskAsync(uri, $"{name}.png");
  92. }
  93. }
  94. }
  95. }
Add Comment
Please, Sign In to add comment