示例#1
0
        private void CancellationTokenCancelQuerie()
        {
            CancellationTokenSource cs = new CancellationTokenSource();

            // Create a task that starts immediately and cancel the token after 4 seconds
            Task cancellationTask = Task.Factory.StartNew(() =>
            {
                var sleepTime = TimeSpan.FromSeconds(5);
                Console.WriteLine($"Waiting For: {sleepTime} ms");
                Thread.Sleep(sleepTime);
                cs.Cancel();
            });

            try
            {
                var result = ParallelQueryRange.AsParallel()
                             .WithCancellation(cs.Token)
                             .Select(number =>
                {
                    Task.Delay(1000).Wait();
                    Console.WriteLine($"Number: {number} | Task: {Task.CurrentId}");
                    return(number);
                }).ToList();
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            catch (AggregateException ex)
            {
                foreach (var inner in ex.InnerExceptions)
                {
                    Console.WriteLine(inner.Message);
                }
            }
        }
 /// <summary>
 /// Enables debugging-friendly execution of a parallelized query by running it sequentially when the debugger is attached or in parallel otherwise.
 /// </summary>
 /// <typeparam name="TSource">The type of elements of source.</typeparam>
 /// <param name="source">A <see cref="ParallelQuery{TSource}"/> on which to set a debug-friendly limit on the degrees of parallelism.</param>
 /// <returns><see cref="ParallelQuery{TSource}"/> representing the same query as <paramref name="source"/>, with the debugging-friendly limit on the degrees of parallelism set.</returns>
 public static ParallelQuery <TSource> AsDebuggable <TSource>(this ParallelQuery <TSource> source) =>
 DebuggableParallel.IsParallel ?
 source :
 source.AsParallel().WithDegreeOfParallelism(1);
示例#3
0
 private static double CalculateMean(
     System.Threading.CancellationToken ct)
 {
     ct.ThrowIfCancellationRequested();
     return(inputIntegers.AsParallel().WithCancellation(ct).Average());
 }
示例#4
0
 static double CalculateMean(CancellationToken ct)
 {
     return(_inputIntegers.AsParallel().WithCancellation(ct).Average());
 }