public static void TestObjectDisposedException()
        {
            IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestObjectDisposedException), new ProgressContext(), false);

            worker.WorkAsync = (ThreadWorkerEventArgs e) =>
            {
                e.Result = new FileOperationContext(String.Empty, ErrorStatus.Success);
                return(Task.FromResult <object>(null));
            };
            try
            {
                worker.Run();
                worker.Join();
            }
            finally
            {
                worker.Dispose();
            }

            bool hasCompleted = false;

            Assert.Throws <ObjectDisposedException>(() => { worker.Run(); });
            Assert.DoesNotThrow(() => { worker.Join(); });
            Assert.DoesNotThrow(() => { hasCompleted = worker.HasCompleted; });
            Assert.That(hasCompleted, "Even though the thread has completed, the variable should be set, since we allow calls to HasCompleted even after Dispose().");
            Assert.DoesNotThrow(() => { worker.Dispose(); });
        }
Esempio n. 2
0
        public static void TestFinishInBackground()
        {
            bool            didComplete = false;
            ProgressContext progress    = new ProgressContext();

            progress.Progressing += (object sender2, ProgressEventArgs e2) =>
            {
                didComplete = true;
            };

            using (IThreadWorker threadWorker = Resolve.Portable.ThreadWorker(nameof(TestFinishInBackground) + "Outer", progress, false))
            {
                threadWorker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    using (WorkerGroup workerGroup = new WorkerGroup(progress))
                    {
                        IThreadWorker worker = workerGroup.CreateWorker(nameof(TestFinishInBackground) + "Inner");
                        worker.WorkAsync = (ThreadWorkerEventArgs e2) =>
                        {
                            e2.Progress.NotifyLevelStart();
                            e2.Progress.NotifyLevelFinished();
                            return(Task.FromResult <object>(null));
                        };
                        worker.Run();
                    }
                    return(Task.FromResult <object>(null));
                };
                threadWorker.Run();
                threadWorker.Join();
            }

            Assert.That(didComplete, "Execution should continue here, with the flag set indicating that the progress event occurred.");
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            ISingleConsumerQueue <TextFileContext> consumerQueue = new MonitorSingleConsumerQueue <TextFileContext>(new TextFileConsumer(FileName));
            IThreadWorker producerThread = new TextFileContextProducer(consumerQueue);
            IThreadWorker consumerThread = consumerQueue;

            try
            {
                consumerThread.Start();
                producerThread.Start();

                Console.WriteLine($"({Thread.CurrentThread.Name}): Модель запущена. Данные пишутся в {Path.Combine(Directory.GetCurrentDirectory(), FileName)}");
                Console.WriteLine($"({Thread.CurrentThread.Name}): Нажмите любую клавишу, чтобы остановить модель.");
                Console.ReadKey(true);
                Console.WriteLine($"({Thread.CurrentThread.Name}): Остановка модели...");
            }
            finally
            {
                producerThread.Dispose();
                consumerThread.Dispose();

                producerThread.Join();
                consumerThread.Join();

                Console.WriteLine($"({Thread.CurrentThread.Name}): Модель остановлена. Нажмите любую клавишу для выхода...");
                Console.ReadKey(true);
            }
        }
        public static void TestProgress()
        {
            FakeRuntimeEnvironment environment = (FakeRuntimeEnvironment)OS.Current;
            int progressCalls = 0;

            ProgressContext progress = new ProgressContext();

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestProgress), progress, false))
            {
                worker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    environment.CurrentTiming.CurrentTiming = TimeSpan.FromSeconds(1);
                    e.Progress.AddCount(1);
                    e.Result = new FileOperationContext(String.Empty, ErrorStatus.Success);
                    return(Task.FromResult <object>(null));
                };
                progress.Progressing += (object sender, ProgressEventArgs e) =>
                {
                    ++progressCalls;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(progressCalls, Is.EqualTo(1), "The Progressing event should be raised exactly one time.");
        }
        public static void TestSimple()
        {
            int workThreadId = -1;
            FileOperationContext returnedStatus = new FileOperationContext(String.Empty, ErrorStatus.UnspecifiedError);

            bool done = false;

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestSimple), new ProgressContext(), false))
            {
                worker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    workThreadId = Thread.CurrentThread.ManagedThreadId;
                    e.Result     = new FileOperationContext(String.Empty, ErrorStatus.Success);
                    return(Task.FromResult <object>(null));
                };
                worker.Completing += (object sender, ThreadWorkerEventArgs e) =>
                {
                    returnedStatus = e.Result;
                    done           = true;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(returnedStatus.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should be returned as successful.");
            Assert.That(workThreadId, Is.Not.EqualTo(Thread.CurrentThread.ManagedThreadId), "The work should not be performed on the caller thread.");
            Assert.That(done, Is.True, "The background work must have executed the completed handler now.");
        }
Esempio n. 6
0
        public static void TestInvalidOperationException()
        {
            using (WorkerGroup workerGroup = new WorkerGroup())
            {
                IThreadWorker worker = workerGroup.CreateWorker(nameof(TestInvalidOperationException));

                bool?f = null;
                Assert.Throws <InvalidOperationException>(() => { f = worker.HasCompleted; });
                Assert.That(!f.HasValue, "No value should be set, since an exception should have occurred.");
                Assert.Throws <InvalidOperationException>(() => { worker.Join(); });
                worker.Abort();
            }
        }
        public static void TestPrepare()
        {
            bool wasPrepared = false;

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestPrepare), new ProgressContext(), false))
            {
                worker.Prepare += (object sender, ThreadWorkerEventArgs e) =>
                {
                    wasPrepared = true;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(wasPrepared, Is.True, "The Prepare event should be raised.");
        }
        public static void TestExceptionDuringWork()
        {
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestExceptionDuringWork), new ProgressContext(), false))
            {
                worker.WorkAsync = (e) =>
                {
                    throw new InvalidOperationException("Something went intentionally wrong.");
                };
                worker.Completed += (sender, e) =>
                {
                    status = e.Result;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Exception));
        }
        public static void TestErrorSetInWorkCompleted()
        {
            bool errorInWork = false;

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestErrorSetInWorkCompleted), new ProgressContext(), false))
            {
                worker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    throw new InvalidOperationException();
                };
                worker.Completing += (object sender, ThreadWorkerEventArgs e) =>
                {
                    errorInWork = e.Result.ErrorStatus == ErrorStatus.Exception;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(errorInWork, Is.True, "The operation was interrupted by an exception and should return status as such.");
        }
        public static void TestCancellationByException()
        {
            bool wasCanceled = false;

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestCancellationByException), new ProgressContext(), false))
            {
                worker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    throw new OperationCanceledException();
                };
                worker.Completing += (object sender, ThreadWorkerEventArgs e) =>
                {
                    wasCanceled = e.Result.ErrorStatus == ErrorStatus.Canceled;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(wasCanceled, Is.True, "The operation was canceled and should return status as such.");
        }
 public static void TestHasCompleted()
 {
     using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestHasCompleted), new ProgressContext(), false))
     {
         bool wasCompletedInWork = false;
         worker.WorkAsync = (ThreadWorkerEventArgs e) =>
         {
             wasCompletedInWork = worker.HasCompleted;
             return(Task.FromResult <object>(null));
         };
         bool wasCompletedInCompleted = false;
         worker.Completing += (object sender, ThreadWorkerEventArgs e) =>
         {
             wasCompletedInCompleted = worker.HasCompleted;
         };
         worker.Run();
         worker.Join();
         Assert.That(!wasCompletedInWork, "Completion is not set as true in the work event.");
         Assert.That(!wasCompletedInCompleted, "Completion is not set as true until after the completed event.");
         Assert.That(worker.HasCompleted, "Completion should be set as true when the thread is joined.");
     }
 }
        public static void TestCancellationByRequest()
        {
            bool wasCanceled = false;
            FakeRuntimeEnvironment environment = (FakeRuntimeEnvironment)OS.Current;

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestCancellationByRequest), new CancelProgressContext(new ProgressContext()), false))
            {
                worker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    e.Progress.Cancel = true;
                    environment.CurrentTiming.CurrentTiming = TimeSpan.FromSeconds(1);
                    e.Progress.AddCount(1);
                    return(Task.FromResult <object>(null));
                };
                worker.Completing += (object sender, ThreadWorkerEventArgs e) =>
                {
                    wasCanceled = e.Result.ErrorStatus == ErrorStatus.Canceled;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(wasCanceled, Is.True, "The operation was canceled and should return status as such.");
        }