Last active
April 28, 2016 01:59
-
-
Save valerysntx/3aed0b0b42bcdbb8d6bf2856b45786ba to your computer and use it in GitHub Desktop.
Async Parallel Collection Projections
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
| public struct FromAsyncTaskResult{ | |
| public int result; | |
| }; | |
| void Main(){ | |
| MainNew().GetAwaiter().GetResult(); | |
| } | |
| async Task<FromAsyncTaskResult[]> MainNew() | |
| { | |
| var bag = new List<FromAsyncTaskResult>(); | |
| var slim = new SemaphoreSlim(1,5); | |
| // Truncate observable sequence after receiving 5 events | |
| var tasks = | |
| Enumerable.Range(0,10) | |
| .AsParallel() | |
| .Select(async (f)=> | |
| { | |
| slim.Wait(); | |
| try{ | |
| Console.WriteLine(string.Format("[{0}]-{2} {1}",Thread.CurrentThread.ManagedThreadId, f, DateTime.Now)); | |
| await Task.Delay(1000); | |
| return new FromAsyncTaskResult | |
| { | |
| result = await Observable.FromAsync(async ()=> await | |
| Task.Run(async ()=> await Task.FromResult(f)).ConfigureAwait(false) | |
| ) | |
| }; | |
| } finally { | |
| slim.Release(); | |
| } | |
| }); | |
| var tasksQueryStartAll = tasks.Select( | |
| async (x)=>{ | |
| return await x.ConfigureAwait(false); | |
| }).ToArray(); | |
| tasksQueryStartAll.Dump(); | |
| return await Task.WhenAll(tasksQueryStartAll); | |
| } | |
| //block thread... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment