예제 #1
0
        public void SimpleTest()
        {
            var task = threadPool.Submit <int>(() => 2 * 2);

            Assert.AreEqual(4, task.Result);
            Assert.IsTrue(task.IsCompleted);
        }
예제 #2
0
        public void ContinueWorkAfterShutdownTest()
        {
            threadPool = new MyThreadPool(2);
            var task1 = threadPool.Submit(() => 5 * 7);

            threadPool.Shutdown();
            Assert.Throws <InvalidOperationException>(() => threadPool.Submit(() => 2 + 1));
        }
예제 #3
0
        public void SimpleContinueWithTest()
        {
            threadPool = new MyThreadPool(1);
            var task = threadPool.Submit <int>(() => 2 * 2).ContinueWith(x => x * 3);

            Assert.AreEqual(12, task.Result);
            Assert.IsTrue(task.IsCompleted);
        }
예제 #4
0
        public void CorrectNumberOfThreadsTest()
        {
            int    countOfThreads = 0;
            Object locker         = new object();

            threadPool = new MyThreadPool(Environment.ProcessorCount);
            for (int iter = 0; iter < 7; iter++)
            {
                threadPool.Submit(() =>
                {
                    lock (locker)
                    {
                        countOfThreads++;
                        Thread.Sleep(30);
                        return(1);
                    }
                });
            }
            Thread.Sleep(700);
            Assert.IsTrue(Environment.ProcessorCount <= countOfThreads);
        }
            /// <summary>
            /// Apply new function to a previous result.
            /// </summary>
            public IMyTask <TNewResult> ContinueWith <TNewResult>(Func <TResult, TNewResult> newFunc)
            {
                if (newFunc == null)
                {
                    throw new ArgumentNullException("Input function equals null.");
                }
                if (this.threadPool.cancellationTokenSource.IsCancellationRequested)
                {
                    throw new ApplicationException("Shutdown method has alredy been called.");
                }

                lock (locker)
                {
                    if (this.IsCompleted)
                    {
                        return(threadPool.Submit(() => newFunc(result)));
                    }

                    var newTask = new MyTask <TNewResult>(() => newFunc(result), threadPool);
                    this.submitFunctionsQueue.Enqueue(newTask.Execute);
                    return(newTask);
                }
            }