Created
March 11, 2013 05:39
-
-
Save droyad/5132102 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void Main() | |
| { | |
| var result = MakeCalls("ABCDEFGHIJKLMNOP", c => CallWebService(c), 2).Result; | |
| result.Dump(); | |
| } | |
| public async System.Threading.Tasks.Task<string> CallWebService(char c) | |
| { | |
| await System.Threading.Tasks.Task.Delay(2000); | |
| return c.ToString() + DateTime.Now.Second.ToString(); | |
| } | |
| public async System.Threading.Tasks.Task<IEnumerable<TReturn>> MakeCalls<T, TReturn>(IEnumerable<T> items, Func<T, System.Threading.Tasks.Task<TReturn>> func, int maxDegreeeOfParallelism) | |
| { | |
| var allTasks = new List<System.Threading.Tasks.Task<TReturn>>(); | |
| var throttler = new SemaphoreSlim(maxDegreeeOfParallelism); | |
| foreach (var item in items) | |
| { | |
| var localItem = item; | |
| // do an async wait until we can schedule again | |
| await throttler.WaitAsync(); | |
| allTasks.Add(System.Threading.Tasks.Task.Run(async () => | |
| { | |
| try | |
| { | |
| return await func(localItem); | |
| } | |
| finally | |
| { | |
| throttler.Release(); | |
| } | |
| })); | |
| } | |
| // won't get here until all urls have been put into tasks | |
| await System.Threading.Tasks.Task.WhenAll(allTasks); | |
| // won't get here until all tasks have completed in some way | |
| // (either success or exception) | |
| return allTasks.Select(t => t.Result); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment