Beispiel #1
0
        public void TaskAllSequentialMethodCombinesTasksSequentially()
        {
            const int   taskCount     = 10;
            const int   taskTime      = 50; //ms
            const float tolerance     = 50; //ms
            int         tasksExecuted = 0;
            int         accessCounter = 0;

            Func <UnityTask>[] tasks   = new Func <UnityTask> [taskCount];
            List <Thread>      threads = new List <Thread>(taskCount);

            for (int i = 0; i < taskCount; i++)
            {
                int i_ = i; // Copy i for lambdas

                UnityTask task   = new UnityTask();
                Thread    thread = new Thread((object count) =>
                {
                    try
                    {
                        int count_ = (int)count;

                        Assert.AreEqual(accessCounter, 0, "Two tasks are executing simulaniously");
                        accessCounter++;

                        Assert.AreEqual(tasksExecuted, count_, "Tasks executed should be equal to the current index");
                        Thread.Sleep(taskTime);
                        Assert.AreEqual(tasksExecuted, count_, "Tasks executed should be equal to the current index");

                        tasksExecuted++;

                        accessCounter--;
                        task.Resolve();
                    }
                    catch (Exception e)
                    {
                        task.Reject(e);
                    }
                });

                tasks[i_] = () => { thread.Start(i_); return(task); };

                threads.Add(thread);
            }

            DateTime startTime = DateTime.Now;
            object   result    = UnityTask.AllSequential(tasks).Result; // Result blocks until finished
            TimeSpan totalTime = DateTime.Now - startTime;

            Assert.AreEqual((float)taskTime * taskCount, totalTime.TotalMilliseconds, tolerance);
        }