示例#1
0
        /// <summary>
        /// Загружка выбранных записей.
        /// </summary>
        private void Download()
        {
            var infos = new[] { teAnalyseUri.Text };

            if (!Directory.Exists(teDownloadPath.Text))
            {
                Directory.CreateDirectory(teDownloadPath.Text);
            }

            File.WriteAllLines(Path.Combine(teDownloadPath.Text, "_Info.txt"), infos);

            _threadPool           = new FixedThreadPool(Global.Default.varXml.ThreadCount);
            _threadPool.Finished += ThreadPool_Finished;

            foreach (var record in _records)
            {
                record.ProgressPercentage = 0;
            }

            var uri = new Uri(teAnalyseUri.Text);

            var downloads = _records.Where(item => item.Priority != Priority.None);

            var log    = (int)Math.Log10(_records.Count) + 1;
            var format = $"D{log}";

            foreach (var record in downloads)
            {
                var act = new Action(() =>
                                     DownloadRecord($"{uri.Authority}{record.Reference}",
                                                    teDownloadPath.Text,
                                                    $"{record.Index.ToString(format)}. {record.Title}",
                                                    record));

                switch (record.Priority)
                {
                case Priority.High:
                    _threadPool.Execute(act, TaskPriorityEx.HIGH);
                    break;

                case Priority.Normal:
                    _threadPool.Execute(act, TaskPriorityEx.NORMAL);
                    break;

                case Priority.Low:
                    _threadPool.Execute(act);
                    break;
                }
            }
        }
示例#2
0
        public void ExecuteTest_TwoPoolNoPriority()
        {
            TestConditions result = new TestConditions();

            FixedThreadPool pool     = new FixedThreadPool(2);
            DateTime        started1 = DateTime.MinValue;
            DateTime        started2 = DateTime.MinValue;
            DateTime        started3 = DateTime.MinValue;

            DateTime t0 = DateTime.Now;
            TimeSpan t1, t2, t3;

            if (!pool.Execute(() => { started1 = DateTime.Now; Console.WriteLine("Task 1"); Thread.Sleep(1000); }))
            {
                result.Add(() => false, () => "Void Execute return FALSE unexpectedly");
            }

            if (!pool.Execute(() => { started2 = DateTime.Now; Console.WriteLine("Task 2"); Thread.Sleep(1000); }))
            {
                result.Add(() => false, () => "Void Execute return FALSE unexpectedly");
            }

            Thread.Sleep(2500);

            if (!pool.Execute(() => { started3 = DateTime.Now; Thread.Sleep(100); Console.WriteLine("Task 3"); }))
            {
                result.Add(() => false, () => "Void Execute return FALSE unexpectedly");
            }

            Thread.Sleep(500);

            t1 = started1 - t0;
            t2 = started2 - t0;
            t3 = started3 - t0;


            result.Add(() => 0 <= t1.TotalMilliseconds && t1.TotalMilliseconds < 500,
                       () => string.Format("t1 = {0} != [0; 500)", t1.TotalMilliseconds));

            result.Add(() => 0 <= t2.TotalMilliseconds && t2.TotalMilliseconds < 500,
                       () => string.Format("t2 = {0} != [0; 500)", t2.TotalMilliseconds));

            result.Add(() => 2500 < t3.TotalMilliseconds && t3.TotalMilliseconds < 3000,
                       () => string.Format("t3 = {0} != (2500; 3000)", t3.TotalMilliseconds));

            result.Print();

            Assert.IsTrue(result.Calculate());
        }
        public void ExecuteTask_ReturnsTrue()
        {
            var    pool = new FixedThreadPool(1);
            Action task = () => Thread.Sleep(1000);

            Assert.That(pool.Execute(task), Is.EqualTo(true));
        }
        public void TestStartOrder()
        {
            int maxThreads = 3;

            string plannedPriorities  = "lhhnhhnlhnlhnlllhhhnnnhnhnhhlllhhhnnhn";
            string expectedPriorities = "hhhnhhhnhhhnhhhnhhhnhhnnnnnnnlllllllll";

            var pool = new FixedThreadPool(maxThreads);

            StringBuilder actualPriorities = new StringBuilder();

            for (int i = 0; i < plannedPriorities.Length; i++)
            {
                var task = new TestTask(i.ToString(), ToPriority(plannedPriorities[i]), 100);
                task.OnStart = (t) => { lock (actualPriorities) actualPriorities.Append(t.Priority.ToString().ToLower()[0]); };

                pool.Execute(task, task.Priority);
            }

            while (expectedPriorities.Length > actualPriorities.Length)
            {
                Thread.Sleep(100);
            }

            var actualPrioritiesStr = actualPriorities.ToString();

            Assert.AreEqual(expectedPriorities, actualPrioritiesStr);
        }
示例#5
0
        public void Should_Start_While_Not_Stopped()
        {
            var threadPool = new FixedThreadPool(1);

            var enqueued = threadPool.Execute(MockRepository.GenerateStub <ITask>(), Priority.NORMAL);

            Assert.True(enqueued);
        }
        public void FixedThreadPool_Execute_TestRun()
        {
            var pool = new FixedThreadPool(2);

            for (int i = 0; i < 100; i++)
            {
                pool.Execute(new Task(), (Priority) new Random().Next(3));
            }
        }
示例#7
0
        public async Task Execute_Planed_Tasks()
        {
            var count = 0;

            _threadPool.Execute(new ActionTask(() => Interlocked.Increment(ref count)), Priority.NORMAL);
            await _threadPool.Stop();

            Assert.Equal(1, count);
        }
示例#8
0
        static void Main(string[] args)
        {
            FixedThreadPool pool = new FixedThreadPool(1);

            pool.Execute(() => { Console.WriteLine("test"); Thread.Sleep(1000); });

            Thread.Sleep(10000);

            Console.ReadLine();
        }
示例#9
0
        public void Should_Not_Start_Task_When_Stopped()
        {
            var threadPool = new FixedThreadPool(1);

            threadPool.Stop();

            var enqueued = threadPool.Execute(MockRepository.GenerateStub <ITask>(), Priority.HIGH);

            Assert.False(enqueued);
        }
        public void TestStop()
        {
            var pool = new FixedThreadPool(5);

            TestTask task = new TestTask("1", State.Priority.Normal, 1000);

            bool addResult = pool.Execute(task, task.Priority);

            Assert.AreEqual(true, addResult);

            Thread.Sleep(2000);

            Assert.AreEqual(true, task.IsStarted);
            Assert.AreEqual(true, task.IsStopped);

            pool.Stop();
            addResult = pool.Execute(task, State.Priority.Normal);
            Assert.AreEqual(false, addResult);
        }
        public void ExecuteTask_WhenPoolIsStopped_ReturnsFalse()
        {
            var    pool = new FixedThreadPool(1);
            Action task = () => Thread.Sleep(1000);

            pool.Stop();

            Assert.That(pool.IsStopped, Is.EqualTo(true));
            Assert.That(pool.Execute(task), Is.EqualTo(false));
        }
示例#12
0
        private static async Task ExecuteTasks(FixedThreadPool threadPool, int numberOfTasks)
        {
            Console.WriteLine($"{numberOfTasks} tasks will be executed.");
            var random = new Random();

            for (var i = 0; i < numberOfTasks; i++)
            {
                var priority = (Priority)random.Next((int)Priority.High, (int)Priority.Low + 1);
                var taskDelayInMilliseconds = random.Next(10, 1000);
                var task = new ShowTask(taskDelayInMilliseconds);
                await threadPool.Execute(task, priority);
            }
        }
示例#13
0
        public void Should_Execute_All_Tasks_On_Stop()
        {
            var tasks = Enumerable.Range(1, 1000).Select(i => MockRepository.GenerateMock <ITask>()).ToList();

            tasks.ForEach(task => task.Expect(t => t.Execute()).WhenCalled(mi => Thread.Sleep(1))); // искусственная задержка

            var threadPool = new FixedThreadPool(100);

            tasks.ForEach(task => threadPool.Execute(task, Priority.HIGH));

            threadPool.Stop();

            tasks.ForEach(task => task.VerifyAllExpectations());
        }
示例#14
0
        static void Main(string[] args)
        {
            var commandArgs = ParseCommandArgs(args);

            if (commandArgs == null)
            {
                PrintHelp();
                return;
            }

            Console.WriteLine($"Starting {commandArgs.NumTasks} tasks with {commandArgs.NumThreads} threads.");
            Console.WriteLine();

            try
            {
                var threadPool = new FixedThreadPool(commandArgs.NumThreads);

                var rnd = new Random(1);

                var stdWriters = Enumerable.Range(1, commandArgs.NumTasks)
                                 .Select(i => new StdOutWriter(GeneratePriority(rnd), commandArgs.Delay));

                var sw = new Stopwatch();
                sw.Start();

                foreach (var stdWriter in stdWriters)
                {
                    threadPool.Execute(stdWriter, stdWriter.Priority);
                }

                threadPool.Stop();

                sw.Stop();

                Console.WriteLine();
                Console.WriteLine(sw.Elapsed);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine();

                PrintHelp();
            }
        }
示例#15
0
 private static async Task StartTasks(FixedThreadPool threadPool, Priority priority, int count)
 {
     await Task.Run(() =>
     {
         foreach (var ind in Enumerable.Range(0, count))
         {
             threadPool.Execute(new ActionTask(
                                    () =>
             {
                 var delay = _random.Next(1000) / 1000.0;
                 Thread.Sleep(TimeSpan.FromSeconds(delay));
                 Console.WriteLine($"Task with priority {priority} number {ind} fromy thread Id = {Thread.CurrentThread.ManagedThreadId}, complexity = {delay}");
             }),
                                priority);
         }
     }
                    );
 }
        public void ExecuteTasks_Faster_InManyThreadsThanInOneThread(int times = 2, int threads = 8)
        {
            Action task      = () => Thread.Sleep(1000);
            var    stopwatch = new Stopwatch();
            var    successes = 0;

            for (var i = 0; i < times; i++)
            {
                var oneThreadPool = new FixedThreadPool(1);
                stopwatch.Restart();
                for (var j = 0; j < threads; j++)
                {
                    oneThreadPool.Execute(task);
                }
                oneThreadPool.Stop();
                stopwatch.Stop();
                var oneThreadTime = stopwatch.Elapsed;

                var multiThreadPool = new FixedThreadPool(threads);
                stopwatch.Restart();
                for (var j = 0; j < threads; j++)
                {
                    multiThreadPool.Execute(task);
                }
                multiThreadPool.Stop();
                stopwatch.Stop();
                var multiThreadTime = stopwatch.Elapsed;

                if (multiThreadTime < oneThreadTime)
                {
                    successes++;
                }
            }

            Assert.That(successes, Is.EqualTo(times));
        }
示例#17
0
        /// <summary>
        /// Метод тестрирования под различным количеством потоквов.
        /// </summary>
        /// <param name="poolCount"></param>
        public void ExecuteTest_AnyPoolWithPriority(int poolCount)
        {
            TestConditions result = new TestConditions();

            // перенос из стека в память.
            int poolCountCopy = (int)(object)poolCount;

            FixedThreadPool pool = new FixedThreadPool(poolCountCopy);

            Collection <TaskInfo> infoInit  = new Collection <TaskInfo>();
            Collection <TaskInfo> infoAfter = new Collection <TaskInfo>();

            Random rnd = new Random();
            int    pr;

            const int attemps = 100;

            for (int i = 0; i < attemps; i++)
            {
                TaskPriorityEx priority;
                pr = rnd.Next(0, 3);

                switch (pr)
                {
                case 0:
                    priority = TaskPriorityEx.LOW;
                    break;

                case 1:
                    priority = TaskPriorityEx.NORMAL;
                    break;

                case 2:
                    priority = TaskPriorityEx.HIGH;
                    break;

                default:
                    priority = TaskPriorityEx.LOW;
                    break;
                }

                int copyI = i;
                infoInit.Add(new TaskInfo(copyI, priority, DateTime.Now));
                if (!pool.Execute(
                        () =>
                {
                    infoAfter.Add(new TaskInfo(copyI, priority, DateTime.Now));
                    Console.WriteLine(string.Format("Task {0} {1}", copyI, priority));
                    Thread.Sleep(30);
                },
                        priority))
                {
                    result.Add(() => false, () => "Void Execute return FALSE unexpectedly");
                }
            }

            Thread.Sleep((int)(attemps * 30 / (double)poolCountCopy) + 1000);

            int            noNormalCount = 0;
            int            normalStep    = 0;
            TriggerT <int> trgNormal     = new TriggerT <int>();

            for (int i = 0; i < attemps; i++)
            {
                int copyI = i;
                if (i < poolCountCopy)
                {
                    IEnumerable <TaskInfo> infors = infoInit.Where(item => item.Id == infoAfter[i].Id);
                    if (infors.Count() > 0)
                    {
                        infoInit.Remove(infors.First());
                    }
                    else
                    {
                        result.Add(() => false, () => string.Format("{0} is bad", copyI));
                    }
                }
                else
                {
                    IEnumerable <TaskInfo> infors = infoInit.Where(item => item.Id == infoAfter[i].Id);
                    if (infors.Count() > 0)
                    {
                        if (infors.First().Priority == TaskPriorityEx.NORMAL)
                        {
                            normalStep = i;
                        }
                        else
                        {
                            if (normalStep == 0)
                            {
                                noNormalCount++;
                            }
                        }

                        if (noNormalCount > 5)
                        {
                            result.Add(() => false, () => string.Format("{0} - NORMAL doesn't exist to long", copyI));
                        }

                        int normalStCp = normalStep;

                        if (normalStCp < 30)
                        {
                            if (trgNormal.Calculate(normalStep))
                            {
                                result.Add(() =>
                                {
                                    if (infoAfter[normalStCp + 1].Priority == TaskPriorityEx.HIGH &&
                                        infoAfter[normalStCp + 2].Priority == TaskPriorityEx.HIGH &&
                                        infoAfter[normalStCp + 3].Priority == TaskPriorityEx.HIGH &&
                                        infoAfter[normalStCp + 4].Priority == TaskPriorityEx.NORMAL)
                                    {
                                        return(true);
                                    }
                                    else
                                    {
                                        return(false);
                                    }
                                }, () => string.Format("{0} - Not accurate orders of HIGH and NORMAL", copyI));
                            }
                        }

                        infoInit.Remove(infors.First());
                    }
                    else
                    {
                        result.Add(() => false, () => string.Format("{0} - is bad", copyI));
                    }
                }
            }

            result.Print();
            Assert.IsTrue(result.Calculate());
        }