2

I'm trying to download a list of files (using reactive extensions), maintaining maximum TWO parallel downloads at a time.

So far I didn't come across a working sample.

The closest thing so far is :

How can I limit Parallel.ForEach?

But I want to do the same that via Rx.net Any help would be really appreciated.

Community
  • 1
  • 1
Abu Abdullah
  • 4,004
  • 1
  • 17
  • 15

1 Answers1

3

Observable.Merge takes a maxConcurrent argument which lets you limit how many parallel subscriptions are maintained. So you can do something like this:

public class DownloadResult { /*...*/ }

public Task<DownloadResult> DownloadFileAsync(string path) { /*...*/ }


public IObservable<DownloadResult> DownloadFiles(int maxConcurrent, string[] paths)
{
    return paths
        .Select(path => Observable.FromAsync(() => DownloadFileAsync(path)))
        .Merge(maxConcurrent: maxConcurrent);
}
Brandon
  • 38,310
  • 8
  • 82
  • 87
  • Thanks for the help. I ran your script with linqpad but it won't yield the desired result. Can you please comment on this : http://pastebin.com/5WBQXQv5 – Abu Abdullah Jul 10 '14 at 08:16
  • 2
    yes your `DownloadAsync` isnt really async. Never `new` a Task. Use `Task.Run` instead. Or declare your method `async` and get rid of the Task construction and use `await Task.Delay(1000);` instead of `Sleep` – Brandon Jul 10 '14 at 10:37