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)); }
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))); }
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)); }
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. }); }
/** * <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(); }
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); }
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); }
public void DispatchSyncRunsNormally() { var q = new SerialQueue(new InvalidThreadPool()); var hit = new List <int>(); q.DispatchSync(() => { hit.Add(1); }); CollectionAssert.AreEqual(new[] { 1 }, hit); }
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)); }); }
public void CantCallDispatchAsyncOnDisposedQueue() { var sq = new SerialQueue(invalidPool); sq.Dispose(); var hit = new List <int>(); AssertEx.Throws <ObjectDisposedException>(() => { sq.DispatchAsync(() => hit.Add(1)); }); }
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; }
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))); }
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); }
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); }
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); }
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)); }
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); }
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); }
// 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, () => { }); }
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); }
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); }
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(); }
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)); }
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); }