Пример #1
0
        public void ThreadsCountTest()
        {
            const int n          = 5;
            var       threadPool = new MyThreadPool.MyThreadPool(n);

            Assert.AreEqual(n, threadPool.AliveThreadsCount());
        }
Пример #2
0
        public void ExceptionTest()
        {
            var threadPool = new MyThreadPool.MyThreadPool(1);

            int ZeroDivide()
            {
                int x = 0;

                return(5 / x);
            }

            var wrongTask = threadPool.AddTask(ZeroDivide);

            Action wrongAction =
                () =>
            {
                int result = wrongTask.Result;
            };

            Assert.ThrowsException <AggregateException>(() => wrongTask.Result);

            try
            {
                int result = wrongTask.Result;
            }
            catch (AggregateException ae)
            {
                foreach (Exception ex in ae.InnerExceptions)
                {
                    Assert.ThrowsException <DivideByZeroException>(() => throw ex);
                }
            }
        }
Пример #3
0
        public void ShutdownTest()
        {
            const int n          = 5;
            var       threadPool = new MyThreadPool.MyThreadPool(n);

            int Pow()
            {
                int a = 1963889993;
                int p = 1980589433;

                int res = 1;

                for (int i = 0; i < p; i++)
                {
                    res *= a;
                }

                return(res);
            }

            var heavyTask = threadPool.AddTask(Pow);

            Assert.AreEqual(n, threadPool.AliveThreadsCount());

            threadPool.Shutdown();

            Thread.Sleep(10);
            Assert.AreEqual(1, threadPool.AliveThreadsCount());
            Assert.AreEqual(Pow(), heavyTask.Result);

            Thread.Sleep(500);
            Assert.AreEqual(0, threadPool.AliveThreadsCount());
        }
Пример #4
0
        static void Main(string[] args)
        {
            const int FibonacciCalculations = 3;

            // One event is used for each Fibonacci object.
            ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
            Fibonacci[]        fibArray   = new Fibonacci[FibonacciCalculations];
            Random             random     = new Random();

            // Configure and start threads using ThreadPool.
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                Fibonacci f = new Fibonacci(random.Next(5, 10), doneEvents[i]);
                fibArray[i] = f;

                MyThreadPool.QueueUserWorkItem(f.ThreadPoolCallback);
            }

            // Wait for all threads in pool to calculate.
            WaitHandle.WaitAll(doneEvents);
            Console.WriteLine("All calculations are complete.");

            // Display the results.
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                Fibonacci f = fibArray[i];
                Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
            }

            Console.Read();
        }
Пример #5
0
        public void CalculationsWithException()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var i      = 8;
            var task   = myThreadPool.AddTask(() => 1 / (i - 8));
            var result = task.Result;
        }
Пример #6
0
 /// <summary>
 /// Конструктор класса задач без аргументов, инициализует значения для дальнейшей работы
 /// с задачей.
 /// </summary>
 /// <param name="func">Функция, на основе которой создается задача для пула потоков.</param>
 /// <param name="poolQueue">
 /// Ссылка на очередь задач из пула для добавления новых.
 /// Требуется для работы функции ContinueWith.
 /// </param>
 public MyTask(Func <TResult> func, MyThreadPool pool)
 {
     this.task          = func;
     this.isCompleted   = false;
     this.pool          = pool;
     this.continueQueue = new Queue <Action>();
     this.error         = false;
     this.ready         = new ManualResetEvent(false);
 }
Пример #7
0
        public void ExceptionMustNotStopProgram()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var i    = 8;
            var task = myThreadPool.AddTask(() => 1 / (i - 8));

            myThreadPool.Shutdown();
        }
Пример #8
0
        public void CalculationsWithExceptionInConrinueWith()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var task      = myThreadPool.AddTask(() => 42);
            var newTask   = task.ContinueWith <int>(i => throw new Exception());
            var result    = task.Result;
            var newResult = newTask.Result;
        }
Пример #9
0
        public void ExceptionInContinueWithMustNotStopProgram()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var task    = myThreadPool.AddTask(() => 42);
            var newTask = task.ContinueWith <int>(i => throw new Exception());
            var result  = task.Result;

            myThreadPool.Shutdown();
        }
Пример #10
0
        public void CheckContinueWithOnce()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var task    = myThreadPool.AddTask(() => 2);
            var newTask = task.ContinueWith(j => Convert.ToString(j));

            Assert.AreEqual(2, task.Result);
            Assert.AreEqual("2", newTask.Result);

            myThreadPool.Shutdown();
        }
Пример #11
0
        public void SimpleTest()
        {
            var threadPool = new MyThreadPool.MyThreadPool(1);

            string SayHello() => "Hello";

            var helloTask = threadPool.AddTask <string>(SayHello);

            if (!helloTask.IsCompleted)
            {
                Thread.Sleep(500);
            }

            Assert.AreEqual("Hello", helloTask.Result);
        }
Пример #12
0
        public void TryAddTaskToShutThreadPool()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            myThreadPool.Shutdown();

            var taskAmount = 2000;
            var tasks      = new IMyTask <int> [taskAmount];

            for (var i = 0; i < taskAmount; i++)
            {
                tasks[i] = myThreadPool.AddTask(() => 7 * 8);
                Assert.AreEqual(56, tasks[i].Result);
            }
        }
Пример #13
0
        public void CheckItCanSolveTasks()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var taskAmount = 20;
            var tasks      = new IMyTask <int> [taskAmount];

            for (var i = 0; i < taskAmount; i++)
            {
                tasks[i] = myThreadPool.AddTask(new Func <int>(() => 2 * 21));
                Assert.AreEqual(42, tasks[i].Result);
            }

            myThreadPool.Shutdown();
        }
Пример #14
0
        public void TryContinueWithAfterShutdownWhenTaskIsCounted()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var task = myThreadPool.AddTask(() =>
            {
                var answer = DateTime.Now;
                Thread.Sleep(1000);
                return(answer);
            });

            myThreadPool.Shutdown();
            var result    = task.Result;
            var newTask   = task.ContinueWith(i => DateTime.Now.AddMilliseconds(10000));
            var newResult = newTask.Result;
        }
Пример #15
0
        public void LongCalculations()
        {
            var threadAmount = 10;
            var myThreadPool = new MyThreadPool(threadAmount);

            var task = myThreadPool.AddTask(() =>
            {
                var answer = DateTime.Now;
                Thread.Sleep(1000);
                return(answer);
            });
            var newTask = task.ContinueWith(i => DateTime.Now.AddMilliseconds(1000));
            var result  = task.Result;

            result = newTask.Result;

            myThreadPool.Shutdown();
        }
Пример #16
0
        public void SimpleContinueWithTest()
        {
            var threadPool = new MyThreadPool.MyThreadPool(1);

            string SayHello() => "Hello";

            var helloTask = threadPool.AddTask(SayHello);

            string SayWorld(string str) => str + " World!";

            var helloworldTask = helloTask.ContinueWith(SayWorld);

            if (!helloTask.IsCompleted)
            {
                Thread.Sleep(500);
            }

            Assert.AreEqual("Hello", helloTask.Result);
            Assert.AreEqual("Hello World!", helloworldTask.Result);
        }
Пример #17
0
        static void Main(string[] args)
        {
            var task = new Task(() =>
            {
                DataGenerator dg       = new DataGenerator();
                long threadWaitTime    = 2000;
                double growthQuotient  = 0.25;
                int threadNumber       = 5;
                MyThreadPool pool      = new MyThreadPool(dg.standartExecutionTime, threadNumber, threadWaitTime);
                dg.DataGeneratedEvent += (sender, dataGeneratedEventArgs) =>
                {
                    Console.WriteLine(($"{DateTime.Now:hh:mm:ss.fff tt} Сгенерировано задание"));
                    pool.RaiseEvent(Slow, dg.standartExecutionTime);
                };
                dg.Start();
            });

            task.Start();
            Console.ReadLine();
        }
Пример #18
0
        public void BigPoolTest()
        {
            const int n          = 3;
            var       threadPool = new MyThreadPool.MyThreadPool(n);

            string SayHello() => "Hello";
            string SayHelloWorld(string hello) => hello + " world!";

            int TakeFive() => 5;
            int Add(int number) => number + 15;

            bool GetTrue() => true;
            string MakeChoice(bool b) => b ? "Good" : "Bad";
            string Introduce(string str) => str + " boy";

            var helloTask    = threadPool.AddTask(SayHello);
            var takefiveTask = threadPool.AddTask(TakeFive);
            var gettrueTask  = threadPool.AddTask(GetTrue);

            var helloworldTask = helloTask.ContinueWith(SayHelloWorld);
            var addTask        = takefiveTask.ContinueWith(Add);
            var choiceTask     = gettrueTask.ContinueWith(MakeChoice);

            var introduceTask = choiceTask.ContinueWith(Introduce);


            Assert.AreEqual("Hello", helloTask.Result);
            Assert.AreEqual(5, takefiveTask.Result);
            Assert.AreEqual(true, gettrueTask.Result);
            Assert.AreEqual(n, threadPool.AliveThreadsCount());

            Assert.AreEqual("Hello world!", helloworldTask.Result);
            Assert.AreEqual(20, addTask.Result);
            Assert.AreEqual("Good", choiceTask.Result);
            Assert.AreEqual(n, threadPool.AliveThreadsCount());

            Assert.AreEqual("Good boy", introduceTask.Result);
            Assert.AreEqual(n, threadPool.AliveThreadsCount());
        }
Пример #19
0
 public void TestInitialize()
 {
     myThreadPool = new MyThreadPool.MyThreadPool(10);
 }
 public MyTask(Func <TResult> task, MyThreadPool threadPool)
 {
     function        = task;
     this.threadPool = threadPool;
     localQueue      = new Queue <Action>();
 }
Пример #21
0
 /// <summary>
 /// Конструктор экземпляра класса <see cref="MyTask{TResult}"/>.
 /// </summary>
 /// <param name="receivedFunc">Вычисление, которое представляет задача.</param>
 /// <param name="receivedThreadPool">Объект класса <see cref="MyThreadPool"/>,
 /// в котором выполняется задача.</param>
 public MyTask(Func <TResult> func, MyThreadPool threadPool)
 {
     this.func       = func;
     this.threadPool = threadPool;
 }
Пример #22
0
 /// <summary>
 /// Задача — вычисление некоторого значения, описывается в виде Func<TResult>
 /// </summary>
 /// <param name="myThreadPool"> Пул потоков, в котором проходит вычисление</param>
 /// <param name="func"> Сама задача</param>
 public MyTask(MyThreadPool myThreadPool, Func <T> func)
 {
     this.func   = func;
     threadPool  = myThreadPool;
     IsCompleted = false;
 }