Ejemplo n.º 1
0
        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);
        }
        public void ExecuteTask_ReturnsTrue()
        {
            var    pool = new FixedThreadPool(1);
            Action task = () => Thread.Sleep(1000);

            Assert.That(pool.Execute(task), Is.EqualTo(true));
        }
Ejemplo n.º 3
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));
            }
        }
Ejemplo n.º 5
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 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));
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            FixedThreadPool pool = new FixedThreadPool(1);

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

            Thread.Sleep(10000);

            Console.ReadLine();
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
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());
        }
Ejemplo n.º 10
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;
                }
            }
        }
Ejemplo n.º 11
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());
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            var threadPool = new FixedThreadPool(3);

            var producerLow    = StartTasks(threadPool, Priority.LOW, 20);
            var producerHigh   = StartTasks(threadPool, Priority.HIGH, 20);
            var producerNormal = StartTasks(threadPool, Priority.NORMAL, 20);

            Task.WaitAll(producerLow, producerNormal, producerHigh);

            var pool = threadPool.Stop();

            Task.WaitAll(pool);

            Console.ReadKey();
        }
Ejemplo n.º 13
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();
            }
        }
Ejemplo n.º 14
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);
         }
     }
                    );
 }
Ejemplo n.º 15
0
        public static async Task Main()
        {
            var threadPool = new FixedThreadPool(workCount: 9);

            await ExecuteTasks(threadPool, 100);

            await Task.Delay(TimeSpan.FromSeconds(3));

            Console.WriteLine("Add some more tasks.");
            await ExecuteTasks(threadPool, 50);

            await Task.Delay(TimeSpan.FromSeconds(3));

            Console.WriteLine("Stop the thread pool.");
            await threadPool.Stop();

            Console.WriteLine("Simulate executing tasks after the thread pool is stopped.");
            await ExecuteTasks(threadPool, 10);
        }
Ejemplo n.º 16
0
        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 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));
        }
Ejemplo n.º 18
0
 public FixedThreadPoolTests()
 {
     _threadPool = new FixedThreadPool(5);
 }
Ejemplo n.º 19
0
 public LogManager(string log)
 {
     tp      = new FixedThreadPool(1);
     logfile = log;
 }
        /// <summary>
        /// Update the library when invoked via the timer
        /// </summary>
        private void UpdateLibrary()
        {
            try
            {
                // get a hook to the DB
                IDBClient db = Database.RetrieveClient();

                // retrieve the initial number of tracks
                int beforeTracks = Database.RetrieveNumberOfTracks(db);

                // get the audio library locations
                IList <AudioLibraryLocation> locations = Database.RetrieveLibraryLocations(db);

                // get the current timestamp, we'll use this in case anything gets modified while this is happening
                DateTime beforeUpdate = DateTime.Now;

                _log.Info("Starting library update at: " + beforeUpdate.ToLocalTime());

                try
                {
                    // recurse through each of the library locations
                    foreach (AudioLibraryLocation location in locations)
                    {
                        if (_log.IsDebugEnabled)
                        {
                            _log.Debug("Updating library location: " + location.Path);
                        }

                        // initialise the list of directories to process
                        IList <string> directoriesToProcess = new List <string>();

                        // start traversing down each directory
                        ProcessDirectory(directoriesToProcess, location.Path, location.LastWritten);

                        // if there was any processing needed to be done
                        if (directoriesToProcess.Count > 0)
                        {
                            const int numThreads = 5;
                            _libraryThreadPool = new FixedThreadPool(5, ThreadPriority.Lowest);
                            _log.Debug("Created custom thread pool for library with " + numThreads + " threads");

                            // make all the workers
                            for (int i = 0; i < directoriesToProcess.Count; i++)
                            {
                                var worker = new AudioLibraryWorker();
                                worker.Directory = directoriesToProcess[i];

                                // attach it to a worker for the pool
                                var workerItem = new WorkerItem(worker.WorkerMethod);

                                // add it to the pool
                                _libraryThreadPool.QueueWorkerItem(workerItem);

                                // start the show
                                _libraryThreadPool.Start();
                            }
                        }

                        // reset the reference to when this update run started
                        location.LastWritten = beforeUpdate;

                        // store this updated location back in the DB
                        Database.UpdateAddLibraryLocation(db, location);

                        // commit after each location.  if something goes wrong, we wont have to redo
                        db.Commit();
                    }

                    // get the number of tracks after
                    int afterTracks = Database.RetrieveNumberOfTracks(db);

                    TimeSpan elapsedTime = DateTime.Now - beforeUpdate;
                    _log.Info("Finished library update at: " + DateTime.Now.ToLocalTime() + ".  Took: " +
                              elapsedTime.TotalSeconds + " seconds");
                    _log.Info("Imported " + (afterTracks - beforeTracks) + " tracks");

                    // close the db
                    db.Close();
                }
                catch (DatabaseClosedException)
                {
                    _log.Debug("The database has been closed prematurely");
                }
            }
            catch (Db4oException ex)
            {
                _log.Error("Problem occurred when updating library", ex);
            }
            finally
            {
                _libraryUpdateTimer.Start();
            }
        }
Ejemplo n.º 21
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());
        }