private static void AsyncOperations(ComputeAsync lComputeAsync, ulong[] lNumbers, Stopwatch lStopwatch, int waitTime) { CancellationTokenSource tokenSource = new CancellationTokenSource(waitTime); lStopwatch.Restart(); Task lFirst = Task.Run( async() => { foreach (ulong number in lNumbers) { if (tokenSource.Token.IsCancellationRequested) { Console.WriteLine("Cancellation requested"); tokenSource.Token.ThrowIfCancellationRequested(); } Task <ulong> lCompleted = await lComputeAsync.GetFibonacciAsync(number) .ContinueWith(x => lComputeAsync.GetFactorialAsync(x.Result)); Console.WriteLine(lCompleted.Result); } }, tokenSource.Token); try { lFirst.Wait(tokenSource.Token); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.WriteLine($"Async ops: {lStopwatch.ElapsedMilliseconds}"); } }
private static void AsyncOperationWhenAny(ComputeAsync lComputeAsync, ulong[] lNumbers, Stopwatch lStopwatch, int waitTime) { CancellationTokenSource tokenSource = new CancellationTokenSource(waitTime); lStopwatch.Restart(); var lAntecedents = new List <Task <Task <ulong> > >(); foreach (ulong number in lNumbers) { lAntecedents.Add(Task.Run(() => lComputeAsync.GetFibonacciAsync(number) .ContinueWith(x => lComputeAsync.GetFactorialAsync(x.Result)), tokenSource.Token)); } while (lAntecedents.Count > 0) { Task <Task <ulong> > lCompleted = Task.WhenAny(lAntecedents).Result; lAntecedents.Remove(lCompleted); Console.WriteLine(lCompleted.Result.Result); } Console.WriteLine($"Async when any ops: {lStopwatch.ElapsedMilliseconds}"); }