Advertisement
neox84

Rx.NET - Concurrency test

Jul 10th, 2014
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.74 KB | None | 0 0
  1. void Main()
  2. {
  3.     var urls = new[]{ "url1", "url2", "url3", "url4" };
  4.     DownloadFiles(2,urls).Subscribe();
  5.     Thread.Sleep(5000); // delay program quitting to observe threads output
  6. }
  7.  
  8. public class DownloadResult { /*...*/ }
  9.  
  10. public Task<DownloadResult> DownloadFileAsync(string path)
  11. {
  12.     return new Task<DownloadResult>(()=>
  13.     {
  14.         ("Started : " + path).Dump();
  15.         Thread.Sleep(1000); // the download activity (i.e sync method) ... WebClient.DownloadFile
  16.         ("Finished : " + path).Dump();
  17.         return new DownloadResult();
  18.     });
  19. }
  20.  
  21.  
  22. public IObservable<DownloadResult> DownloadFiles(int maxConcurrent, string[] paths)
  23. {
  24.     return paths
  25.         .Select(path => Observable.FromAsync(() => DownloadFileAsync(path)))
  26.         .Merge(maxConcurrent: maxConcurrent);
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement