Exemplo n.º 1
0
        public async Task EnqueueAsyncAction()
        {
            // Assign

            var queue = new SerialQueue();
            var list  = new List <int>();
            var tasks = new List <Task>();
            var range = Enumerable.Range(0, 5000);

            // Act

            foreach (var number in range)
            {
                tasks.Add(queue.Enqueue(async() => {
                    await Task.Delay(1);
                    list.Add(number);
                }));
            }

            await Task.WhenAll(tasks);

            // Assert

            Assert.True(range.SequenceEqual(list));
        }
Exemplo n.º 2
0
        public void EnqueueFromMultipleThreads()
        {
            // Assign

            const int count = 10000;
            var       queue = new SerialQueue();
            var       list  = new List <int>();

            // Act

            var counter = 0;

            for (int i = 0; i < count; i++)
            {
                Task.Run(() => {
                    queue.Enqueue(() => list.Add(counter++));
                });
            }

            while (list.Count != count)
            {
            }
            ;

            // Assert

            Assert.True(list.SequenceEqual(Enumerable.Range(0, count)));
        }
Exemplo n.º 3
0
        public async Task QueueFunction()
        {
            // Assign

            var queue = new SerialQueue();
            var list  = new List <int>();
            var tasks = new List <Task <int> >();
            var range = Enumerable.Range(0, 10000);

            // Act

            foreach (var number in range)
            {
                tasks.Add(queue.Enqueue(() => {
                    list.Add(number);
                    return(number);
                }));
            }

            await Task.WhenAll(tasks);

            // Assert

            Assert.True(tasks.Select(x => x.Result).SequenceEqual(list));
        }
Exemplo n.º 4
0
        public void MultipleConcurrentDispatchAsyncsRunInSerialFollowedByDispatchSync()
        {
            var q   = new SerialQueue(realPool);
            var hit = new List <int>();

            q.DispatchAsync(() => {
                hit.Add(1);
                Thread.Sleep(50);
                hit.Add(2);
            });
            q.DispatchAsync(() => {
                hit.Add(3);
                Thread.Sleep(50);
                hit.Add(4);
            });
            q.DispatchSync(() => {
                hit.Add(5);
            });
            q.DispatchSync(() => {
                hit.Add(6);
            });
            q.DispatchAsync(() => {
                hit.Add(7);
                Thread.Sleep(50);
                hit.Add(8);
            });
            q.DispatchSync(() => {
                hit.Add(9);
            });

            CollectionAssert.AreEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, hit);
        }
        public void TasksRunOneAtATime()
        {
            SerialQueue queue = new SerialQueue(new ManagedThreadPoolDispatcher());

            bool taskRunning = false;

            for (int i = 0; i < 10; ++i)
            {
                queue.DispatchAsync(null, (_) =>
                {
                    Assert.IsFalse(taskRunning);
                    taskRunning = true;

                    Thread.Sleep(TimeSpan.FromMilliseconds(30));

                    Assert.IsTrue(taskRunning);
                    taskRunning = false;
                });
            }

            queue.DispatchSync(null, (_) =>
            {
                // just to ensure that the tests don't finish prematurely.
            });
        }
Exemplo n.º 6
0
        /**
         * <summary>Initializes Cosmos network API</summary>
         * <param name="namespaceId">Bluzelle Database Namespace ID</param>
         * <param name="mnemonic">Mnemonic for account in BIP39</param>
         * <param name="address">Account address in Cosmos format. It'll be verified over given mnemonic</param>
         * <param name="chainId">Database chain ID. For Bluzelle network it equals to "bluzelle"</param>
         * <param name="endpoint">REST API endpoint including protocol and port</param>
         */
        public Cosmos(
            string namespaceId,
            string mnemonic,
            string address,
            string chainId  = "bluzelle",
            string endpoint = "http://testnet.public.bluzelle.com:1317")
        {
            _chainId        = chainId;
            NamespaceId     = namespaceId;
            _sessionPk      = MnemonicToPrivateKey(mnemonic);
            _sessionAddress = GetAddress(_sessionPk.PubKey);

            if (_sessionAddress != address)
            {
                throw new Exceptions.MnemonicInvalidException();
            }

            _restClient = new RestClient(endpoint);
            _restClient.UseNewtonsoftJson(new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                },
                NullValueHandling = NullValueHandling.Ignore
            });

            _transactionQueue = new SerialQueue();

            UpdateAccount();
        }
Exemplo n.º 7
0
        public async Task CatchExceptionFromAsyncAction()
        {
            // Assign

            var queue            = new SerialQueue();
            var exceptionCatched = false;

            // Act

            await queue.Enqueue(() => Thread.Sleep(10));

            try {
                await queue.Enqueue(async() => {
                    await Task.Delay(50);
                    throw new Exception("Test");
                });
            }
            catch (Exception e) {
                if (e.Message == "Test")
                {
                    exceptionCatched = true;
                }
            }

            // Assert

            Assert.True(exceptionCatched);
        }
Exemplo n.º 8
0
        public async Task CatchExceptionFromAsyncFunction()
        {
            // Assign

            var queue            = new SerialQueue();
            var exceptionCatched = false;

            // Act

            await queue.Enqueue(() => Thread.Sleep(10));

            try {
                await queue.Enqueue(asyncFunction : async() => {
                    await Task.Delay(50);
                    throw new Exception("Test");
#pragma warning disable CS0162 // Unreachable code detected
                    return(false);

#pragma warning restore CS0162 // Unreachable code detected
                });
            }
            catch (Exception e) {
                if (e.Message == "Test")
                {
                    exceptionCatched = true;
                }
            }

            // Assert

            Assert.True(exceptionCatched);
        }
Exemplo n.º 9
0
        public void DispatchSyncRunsNormally()
        {
            var q   = new SerialQueue(new InvalidThreadPool());
            var hit = new List <int>();

            q.DispatchSync(() => {
                hit.Add(1);
            });
            CollectionAssert.AreEqual(new[] { 1 }, hit);
        }
Exemplo n.º 10
0
        public void CantCallDispatchAfterOnDisposedQueue()
        {
            var sq = new SerialQueue(invalidPool);

            sq.Dispose();
            var hit = new List <int>();

            AssertEx.Throws <ObjectDisposedException>(() => {
                sq.DispatchAfter(TimeSpan.FromMilliseconds(100), () => hit.Add(1));
            });
        }
Exemplo n.º 11
0
        public void CantCallDispatchAsyncOnDisposedQueue()
        {
            var sq = new SerialQueue(invalidPool);

            sq.Dispose();
            var hit = new List <int>();

            AssertEx.Throws <ObjectDisposedException>(() => {
                sq.DispatchAsync(() => hit.Add(1));
            });
        }
Exemplo n.º 12
0
        public steppersync(SerialQueue sq, List <stepcompress> sc_list, int move_num)
        {
            this.sq = sq;
            cq      = new command_queue();

            this.sc_list = sc_list;
            this.sc_num  = sc_list.Count;

            move_clocks     = new ulong[move_num];
            num_move_clocks = move_num;
        }
Exemplo n.º 13
0
        public string DoCommand(string cmd)
        {
            byte[] buffer = new byte[CReadBufferSize];
            SerialQueue <string> commandQueue = new SerialQueue <string>();

            try
            {
                _serialPort.Write(cmd);

                Console.Write("UP: ");
                foreach (byte b in Encoding.GetBytes(cmd))
                {
                    Console.Write(b.ToString().PadLeft(3, ' '));
                }
                Console.WriteLine();

                Thread.Sleep(5);
            }
            catch (Exception ex)
            {
                LogHelper.WriteS("Error serial writing: " + ex.Message, "SERIAL", LogHelper.MessageTypes.ERROR);
                return(null);
            }

            Thread.Sleep(10);

            //string output = "";
            //int i = 0;
            //do
            //{
            //    _serialPort.Read(buffer, 0, 1024);
            //    output += _serialPort.Encoding.GetString(buffer); // Convert the input bytes to a string.
            //    buffer = new byte[CReadBufferSize];

            //    foreach (byte c in Encoding.GetBytes(output))
            //    {
            //        Console.Write(c + "\t");
            //    }

            //} while (!output.Contains("#"));

            string output = _serialPort.ReadTo("#");

            Console.Write("DN: ");
            foreach (byte b in Encoding.GetBytes(output))
            {
                Console.Write(b.ToString().PadLeft(3, ' '));
            }
            Console.WriteLine();

            return(output);
        }
        public void SyncRunsOnSeparateThreads()
        {
            SerialQueue queue = new SerialQueue(new ManagedThreadPoolDispatcher());

            int threadId = Thread.CurrentThread.ManagedThreadId;

            for (int i = 0; i < 10; ++i)
            {
                queue.DispatchSync(null, (_) =>
                {
                    Assert.AreNotEqual(threadId, Thread.CurrentThread.ManagedThreadId);
                });
            }
        }
        public void SyncRunsSynchronously()
        {
            SerialQueue queue = new SerialQueue(new ManagedThreadPoolDispatcher());

            int numberTest = 0;

            for (int i = 0; i < 100; ++i)
            {
                queue.DispatchSync(null, (_) =>
                {
                    Assert.AreEqual(numberTest++, i);
                });
            }
        }
        public void TimerQueueActuallyFires()
        {
            SerialQueue    queue      = new SerialQueue(new ManagedThreadPoolDispatcher());
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            WaitCallback cb = (_) =>
            {
                waitHandle.Set();
            };

            queue.DispatchAfter(TimeSpan.FromMilliseconds(10), null, cb);

            Assert.IsTrue(waitHandle.WaitOne(TimeSpan.FromSeconds(1)));
        }
Exemplo n.º 17
0
        public void NestedDispatchSyncDoesntDeadlock()
        {
            var q   = new SerialQueue(new InvalidThreadPool());
            var hit = new List <int>();

            q.DispatchSync(() => {
                hit.Add(1);
                q.DispatchSync(() => {
                    hit.Add(2);
                });
                hit.Add(3);
            });
            CollectionAssert.AreEqual(new[] { 1, 2, 3 }, hit);
        }
Exemplo n.º 18
0
        public void DispatchAsyncCanBeCanceled()
        {
            var q   = new SerialQueue(mockPool);
            var hit = new List <int>();
            var d   = q.DispatchAsync(() => hit.Add(1));

            Assert.AreEqual(1, mockPool.Actions.Count);

            d.Dispose();
            Assert.AreEqual(1, mockPool.Actions.Count); // we can't "take it out" of the threadpool as not all threadpools support that

            mockPool.RunNextAction();
            CollectionAssert.AreEqual(new int[0], hit); // lambda didn't run
            Assert.AreEqual(0, mockPool.Actions.Count);
        }
Exemplo n.º 19
0
        public void DispatchAsyncQueuesToThreadpool()
        {
            var q   = new SerialQueue(mockPool);
            var hit = new List <int>();

            q.DispatchAsync(() => {
                hit.Add(1);
            });
            CollectionAssert.AreEqual(new int[0], hit);

            mockPool.RunNextAction();

            CollectionAssert.AreEqual(new[] { 1 }, hit);
            Assert.AreEqual(0, mockPool.Actions.Count);
        }
Exemplo n.º 20
0
        public async Task EnqueueMixed()
        {
            // Assign

            var queue = new SerialQueue();
            var list  = new List <int>();
            var tasks = new List <Task>();
            var range = Enumerable.Range(0, 10000);

            // Act

            foreach (var number in range)
            {
                if (number % 4 == 0)
                {
                    tasks.Add(queue.Enqueue(() => list.Add(number)));
                }
                else if (number % 3 == 0)
                {
                    tasks.Add(queue.Enqueue(() => {
                        list.Add(number);
                        return(number);
                    }));
                }
                else if (number % 2 == 0)
                {
                    tasks.Add(queue.Enqueue(async() => {
                        await Task.Delay(1);
                        list.Add(number);
                    }));
                }
                else
                {
                    tasks.Add(queue.Enqueue(async() => {
                        await Task.Delay(1);
                        list.Add(number);
                        return(number);
                    }));
                }
            }

            await Task.WhenAll(tasks);

            // Assert

            Assert.True(range.SequenceEqual(list));
        }
Exemplo n.º 21
0
        public void DispatchAsyncCanBeSafelyCanceledAfterItsRun()
        {
            var q   = new SerialQueue(mockPool);
            var hit = new List <int>();

            var d = q.DispatchAsync(() => hit.Add(1));

            mockPool.RunNextAction();

            CollectionAssert.AreEqual(new int[] { 1 }, hit);
            Assert.AreEqual(0, mockPool.Actions.Count);

            d.Dispose();

            CollectionAssert.AreEqual(new int[] { 1 }, hit); // lambda didn't run
            Assert.AreEqual(0, mockPool.Actions.Count);
        }
Exemplo n.º 22
0
        public void NestedDispatchSyncInsideDispatchAsyncDoesntDeadlock()
        {
            var q   = new SerialQueue(new TaskThreadPool());
            var hit = new List <int>();
            var mre = new ManualResetEvent(false);

            q.DispatchAsync(() => {
                hit.Add(1);
                q.DispatchSync(() => {
                    hit.Add(2);
                });
                hit.Add(3);
                mre.Set();
            });
            mre.WaitOne();
            CollectionAssert.AreEqual(new[] { 1, 2, 3 }, hit);
        }
Exemplo n.º 23
0
    // Start is called before the first frame update
    void Start()
    {
        DOTween.Init(true, true, LogBehaviour.Verbose).SetCapacity(200, 10);

        SerialQueue queue = new SerialQueue();

        queue.AppendAction(() =>
        {
            Debug.LogError("time:" + Time.time + ",move");
        });
        queue.AppendAction(() =>
        {
            Debug.LogError("time:" + Time.time + ",animation");
        });

        int actionID = ActionManager.GetInstance().PushAction(2, () => { });
    }
Exemplo n.º 24
0
        public void MultipleDispatchAsyncCallsGetProcessedByOneWorker()
        {
            var q   = new SerialQueue(mockPool);
            var hit = new List <int>();

            q.DispatchAsync(() => {
                hit.Add(1);
            });
            q.DispatchAsync(() => {
                hit.Add(2);
            });
            CollectionAssert.AreEqual(new int[0], hit);

            mockPool.RunNextAction();

            CollectionAssert.AreEqual(new[] { 1, 2 }, hit);
            Assert.AreEqual(0, mockPool.Actions.Count);
        }
Exemplo n.º 25
0
        public void DispatchSyncConcurrentWithAnotherDispatchAsyncWorksProperly()
        {
            var q   = new SerialQueue(new TaskThreadPool());
            var hit = new List <int>();
            var are = new AutoResetEvent(false);

            q.DispatchAsync(() => {
                hit.Add(1);
                are.Set();
                Thread.Sleep(100); // we can't block on an event as that would deadlock, we just have to slow it down enough to force the DispatchSync to wait
                hit.Add(2);
            });
            are.WaitOne();
            q.DispatchSync(() => {
                hit.Add(3);
            });

            CollectionAssert.AreEqual(new[] { 1, 2, 3 }, hit);
        }
        public void TasksCompletedInProperSequence()
        {
            int numberTest = 0;

            SerialQueue queue = new SerialQueue(new ManagedThreadPoolDispatcher());

            for (int i = 0; i < 100; ++i)
            {
                int localValue = i;
                queue.DispatchAsync(null, (_) =>
                {
                    Assert.AreEqual(numberTest++, localValue);
                });
            }

            queue.DispatchSync(null, (_) =>
            {
                Assert.AreEqual(numberTest, 100);
            });
        }
        public void TimerQueueFiresInProperOrder()
        {
            SerialQueue    queue      = new SerialQueue(new ManagedThreadPoolDispatcher());
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            int numberOfExecutions = 0;

            bool firstSucceeded  = false;
            bool secondSucceeded = false;
            bool thirdSucceeded  = false;

            WaitCallback first = (_) =>
            {
                firstSucceeded = numberOfExecutions == 0;
                numberOfExecutions++;
            };

            WaitCallback second = (_) =>
            {
                secondSucceeded = numberOfExecutions == 1;
                numberOfExecutions++;
            };

            WaitCallback third = (_) =>
            {
                thirdSucceeded = numberOfExecutions == 2;
                numberOfExecutions++;
                waitHandle.Set();
            };

            queue.DispatchAfter(TimeSpan.FromMilliseconds(15), null, first);
            queue.DispatchAfter(TimeSpan.FromMilliseconds(30), null, second);
            queue.DispatchAfter(TimeSpan.FromMilliseconds(45), null, third);

            Assert.IsTrue(waitHandle.WaitOne(TimeSpan.FromSeconds(1)));

            Assert.IsTrue(firstSucceeded);
            Assert.IsTrue(secondSucceeded);
            Assert.IsTrue(thirdSucceeded);
        }
Exemplo n.º 28
0
        public async Task TestSerialQueue()
        {
            var queue  = new SerialQueue();
            var now    = DateTime.Now;
            var then   = now;
            var ignore = queue.DispatchAfter(() => then = DateTime.Now, TimeSpan.FromSeconds(1));
            await Task.Delay(250);

            then.Should().Be(now);
            await Task.Delay(800);

            then.Should().NotBe(now);

            var testBool = false;

            queue.DispatchSync(() => Volatile.Read(ref testBool)).Should().BeFalse();

            var t = queue.DispatchAfter(() => Volatile.Read(ref testBool), TimeSpan.FromMilliseconds(500));

            Volatile.Write(ref testBool, true);
            (await t).Should().BeTrue();
        }
Exemplo n.º 29
0
        public async Task QueueAsyncFunctionWithResult()
        {
            // Assign

            var queue = new SerialQueue();
            var list  = new List <int>();
            var tasks = new List <Task>();
            var range = Enumerable.Range(0, 100);

            // Act

            foreach (var number in range)
            {
                list.Add(await queue.EnqueueAsyncFunction(async() =>
                {
                    await Task.Delay(50);
                    return(number);
                }));
            }

            // Assert

            Assert.True(range.SequenceEqual(list));
        }
Exemplo n.º 30
0
        public async Task QueueAsyncFunctionAsNormalFunction()
        {
            // Assign

            var  queue   = new SerialQueue();
            bool success = false;

            // Act

            try
            {
                await queue.EnqueueFunction(async() =>
                {
                    await Task.Delay(50);
                });

                success = true;
            }
            catch (Exception)
            {
            }

            Assert.False(success);
        }