Exemple #1
0
        public void ThreadWorker_CancellationToken()
        {
            var finalOutput = new List <string>();
            var bkg         = new ThreadWorker <int, string>();

            CancellationTokenSource cancellor = new CancellationTokenSource();

            bkg.Start(_DoBkgWork, cancellor.Token);
            bkg.OutputResults.DataReceived += _OnOutputDataReceived;

            bkg.InputToProcess.Add(5);
            bkg.InputToProcess.Add(1088050);
            bkg.WhenAllInputProcessingCompleted().ContinueWith(_ =>
            {
                cancellor.Cancel();
                bkg.InputToProcess.Add(1010155001);
                bkg.ShutdownGracefullyAndWaitForCompletion().ContinueWith(_1 =>
                {
                    Assert.IsFalse(bkg.IsActive);
                    string result = String.Join(",", finalOutput);
                    Assert.AreEqual("5,1,88,5", result);
                });
            });

            void _DoBkgWork(ThreadWorkerDataTracker <int, TNone, string> data)
            {
                while (data.ShouldContinue || data.InputToProcess.Any())
                {
                    if (!data.InputToProcess.Any())
                    {
                        Thread.Sleep(0);
                        continue;
                    }

                    // Grab the input state
                    int number = data.InputToProcess.TakeNext();

                    // Process
                    List <string> output = new List <string>();
                    output.AddRange(number.ToString().Split(new[] { '0' }, StringSplitOptions.RemoveEmptyEntries));

                    // Set the output state
                    data.OutputResults.AddRange(output);
                    data.OutputResults.NotifyDataReceived();
                    Thread.Sleep(0);
                }
            }

            void _OnOutputDataReceived(object sender, EventArgs e)
            {
                finalOutput.AddRange(bkg.OutputResults.TakeAll());
            }
        }