コード例 #1
0
        public void Cancellation_Test(int jobCount)
        {
            int sequenceLength = jobCount * 10;
            int cancelTreshold = jobCount * 2;
            int resultTreshold = jobCount * 3;

            var cancellationEvent = new AutoResetEvent(false);
            var cancellationToken = new CancellationToken();

            List <int> results = new List <int>();

            Task task = Task.Run(() => {
                IEnumerable <int> values = Sequence(sequenceLength, 5)
                                           .AsParallel(jobCount)
                                           .AsEnumerable(cancellationToken);

                foreach (int value in values)
                {
                    results.Add(value);
                    if (results.Count == cancelTreshold)
                    {
                        cancellationEvent.Set();
                    }
                }
            });

            cancellationEvent.WaitOne();
            cancellationToken.Cancel();

            task.Wait(timeout)
            .Should().BeTrue("Timeout");

            results.Should().HaveCountLessOrEqualTo(resultTreshold);
        }
コード例 #2
0
        public void Run(CancellationToken cancellationToken, ProfilingType profilingType)
        {
            Guard.NotNull(cancellationToken, nameof(cancellationToken));

            if (thread != null)
            {
                throw new InvalidOperationException();
            }

            thread = new Thread(() => {
                try {
                    Profiler profiler =
                        profilingType != ProfilingType.None ?
                        new Profiler(name, profilingType) :
                        null;
                    Do(cancellationToken, profiler);
                }
                catch (Exception error) {
                    this.error = error;
                    cancellationToken.Cancel();
                }
                finally {
                    outputChannel.Finish();
                }
            })
            {
                Name         = name,
                IsBackground = true
            };
            thread.Start();
        }