public async Task AddCancel() { //**************************************** var MyCollection = new AsyncCollection <int>(1); //**************************************** await MyCollection.Add(42); using (var MySource = new CancellationTokenSource()) { var MyTask = MyCollection.Add(84, MySource.Token); Assert.IsFalse(MyTask.IsCompleted, "Added too early"); MySource.Cancel(); try { await MyTask; Assert.Fail("Wait not cancelled"); } catch (OperationCanceledException) { } } var Result = await MyCollection.Take(); //**************************************** Assert.AreEqual(0, MyCollection.WaitingToAdd, "Tasks unexpectedly waiting"); Assert.AreEqual(42, Result, "Result not as expected"); }
public async Task AddMaximumMaxTime() { //**************************************** var MyCollection = new AsyncCollection <int>(1); ValueTask <bool> MyTask; //**************************************** await MyCollection.Add(42); MyTask = MyCollection.Add(84, TimeSpan.FromMilliseconds(50)); try { await MyTask; Assert.Fail("Should not reach here"); } catch (TimeoutException) { } //**************************************** Assert.AreEqual(1, MyCollection.Count, "Count not as expected"); }
public async Task ProduceFromMultipleThreads() { AsyncCollection <int> collection = new AsyncCollection <int>(); var t1 = Task.Run(() => { for (int i = 0; i < 500; i++) { collection.Add(i * 2); } }); var t2 = Task.Run(() => { for (int i = 0; i < 500; i++) { collection.Add(i * 2 + 1); } }); Task.WhenAll(t1, t2).ContinueWith(t => collection.CompleteAdding()); int counter = 0; await foreach (var item in collection) { counter++; } Assert.AreEqual(counter, 1000); }
public async Task AddMaximumCancel() { //**************************************** var MyCollection = new AsyncCollection <int>(1); ValueTask <bool> MyTask; //**************************************** await MyCollection.Add(42); using (var MyCancelSource = new CancellationTokenSource()) { MyTask = MyCollection.Add(84, MyCancelSource.Token); MyCancelSource.Cancel(); } try { await MyTask; Assert.Fail("Should not reach here"); } catch (OperationCanceledException) { } //**************************************** Assert.AreEqual(1, MyCollection.Count, "Count not as expected"); }
public void CompletedCollectionShouldPreventMoreItemsAdded() { var collection = new AsyncCollection <int>(); collection.Add(1); collection.CompleteAdding(); collection.Add(1); }
public void TestDrainAnApplyNotInInfiniteLoop() { var aq = new AsyncCollection <bool>(); aq.Add(true); var task = Task.Run(() => aq.DrainAndApply(x => aq.Add(x))); Assert.IsTrue(task.Wait(1000)); }
public void StreamClose() { // 管理生命周期,删除RPC流 connection_.ClearStream(stream_id_); responses_.Add(null); messages_.Add(null); Leyoutech.Utility.DebugUtility.Log("StreamReadWrightStream close", $" ID: {stream_id_}"); // 流关闭回调 SafeInvoke(OnClosed, "Stream Closed"); }
public void DrainShouldBlockWhenDataRemoved() { var aq = new AsyncCollection<bool>(); aq.Add(true); aq.Add(true); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available."); var drained = aq.Drain().ToList(); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available."); }
public void DrainShouldBlockWhenDataRemoved() { var aq = new AsyncCollection <bool>(); aq.Add(true); aq.Add(true); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available."); var drained = aq.Drain().ToList(); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available."); }
/// <summary> /// Quit watching /// </summary> public static void Stop() { if (isRunning) { lock (accesslock) { WindowHook.WindowCreated -= new GeneralShellHookEventHandler(WindowCreated); WindowHook.WindowDestroyed -= new GeneralShellHookEventHandler(WindowDestroyed); WindowHook.WindowActivated -= new GeneralShellHookEventHandler(WindowActivated); appQueue.Add(false); isRunning = false; } } }
public void TakeAsyncShouldPlayNiceWithTPL() { const int expected = 200; const int max = 400; var exit = false; var collection = new AsyncCollection <int>(); var dataTask = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); dataTask.ContinueWith(x => exit = true); Parallel.ForEach(Enumerable.Range(0, max).ToList(), new ParallelOptions { MaxDegreeOfParallelism = 20 }, x => { while (exit == false) { collection.Add(x); Thread.Sleep(100); } }); Console.WriteLine("Left in collection: {0}", collection.Count); Assert.That(dataTask.Result.Count, Is.EqualTo(expected)); Assert.That(collection.Count, Is.LessThan(max - expected)); }
public async void TakeAsyncShouldReturnEvenWhileMoreDataArrives() { var exit = false; var collection = new AsyncCollection <int>(); var sw = Stopwatch.StartNew(); var dataTask = collection.TakeAsync(10, TimeSpan.FromMilliseconds(5000), CancellationToken.None); var highVolumeAdding = Task.Factory.StartNew(() => { //high volume of data adds while (exit == false) { collection.Add(1); Thread.Sleep(5); } }); Console.WriteLine("Awaiting data..."); await dataTask; Assert.That(dataTask.Result.Count, Is.EqualTo(10)); Assert.That(sw.ElapsedMilliseconds, Is.LessThan(5000)); exit = true; Console.WriteLine("Waiting to unwind test..."); await highVolumeAdding; }
private void InitializeEmptySegments() { foreach (var offset in _offsetSize.Keys) { _emptySegments.Add(offset); } }
public void ConsumeSyncFromMultipleThreads() { AsyncCollection <int> collection = new AsyncCollection <int>(); int t1Counter = 0; int t2Counter = 0; var t1 = Task.Run(() => { foreach (var item in collection.GetConsumingEnumerable()) { t1Counter++; } }); var t2 = Task.Run(() => { foreach (var item in collection.GetConsumingEnumerable()) { t2Counter++; } }); for (int i = 0; i < 1000; i++) { collection.Add(i); } collection.CompleteAdding(); t1.Wait(); t2.Wait(); Assert.IsTrue(t1Counter > 400); Assert.IsTrue(t2Counter > 400); }
/// <summary> /// Start uploading and watching for new replays /// </summary> public async void Start() { if (_initialized) { return; } _initialized = true; _uploader = new Uploader(); _analyzer = new Analyzer(); _monitor = new Monitor(); var replays = ScanReplays(); Files.AddRange(replays); replays.Where(x => x.UploadStatus == UploadStatus.None).Reverse().Map(x => processingQueue.Add(x)); _monitor.ReplayAdded += async(_, e) => { await EnsureFileAvailable(e.Data, 3000); var replay = new ReplayFile(e.Data); Files.Insert(0, replay); processingQueue.Add(replay); }; _monitor.Start(); _analyzer.MinimumBuild = await _uploader.GetMinimumBuild(); for (int i = 0; i < MaxThreads; i++) { Task.Run(UploadLoop).Forget(); } }
public void TakeAsyncShouldBeThreadSafe() { const int expected = 10; const int max = 100; var exit = false; var collection = new AsyncCollection <int>(); var take1 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); var take2 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); var take3 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); take1.ContinueWith(t => Console.WriteLine("Take1 done...")); take2.ContinueWith(t => Console.WriteLine("Take2 done...")); take3.ContinueWith(t => Console.WriteLine("Take3 done...")); Task.WhenAll(take1, take2, take3).ContinueWith(x => exit = true); Parallel.ForEach(Enumerable.Range(0, max).ToList(), new ParallelOptions { MaxDegreeOfParallelism = 20 }, x => { while (exit == false) { collection.Add(x); Thread.Sleep(100); } }); Console.WriteLine("Left in collection: {0}", collection.Count); Assert.That(take1.Result.Count, Is.EqualTo(expected)); Assert.That(take2.Result.Count, Is.EqualTo(expected)); Assert.That(take3.Result.Count, Is.EqualTo(expected)); Assert.That(collection.Count, Is.LessThan(max - (expected * 3))); }
private Task <byte[]> EnqueueReadTask(int readSize, CancellationToken cancellationToken) { var readTask = new SocketPayloadReadTask(readSize, cancellationToken); _readTaskQueue.Add(readTask); return(readTask.Tcp.Task); }
public async Task TakeCancel() { //**************************************** var MyCollection = new AsyncCollection <int>(); //**************************************** using (var MySource = new CancellationTokenSource()) { var MyTask = MyCollection.Take(MySource.Token); Assert.IsFalse(MyTask.IsCompleted, "Took too early"); MySource.Cancel(); try { _ = await MyTask; Assert.Fail("Wait not cancelled"); } catch (OperationCanceledException) { } } await MyCollection.Add(42); //**************************************** Assert.AreEqual(0, MyCollection.WaitingToTake, "Tasks unexpectedly waiting"); }
public static void Stop() { if (_IsRunning) { lock (_Accesslock) { if (_mh != null) { _mh.MouseAction -= MListener; _mh.Stop(); _mh = null; } _kQueue.Add(false); _IsRunning = false; } } }
public async Task AddMaximum() { //**************************************** var MyCollection = new AsyncCollection <int>(1); //**************************************** await MyCollection.Add(42); var MyTask = MyCollection.Add(84); //**************************************** Assert.IsFalse(MyTask.IsCompleted, "Added over the maximum"); Assert.AreEqual(1, MyCollection.Count, "Count not as expected"); Assert.AreEqual(1, MyCollection.WaitingToAdd, "Waiting adders not as expected"); }
private Task <KafkaDataPayload> EnqueueWriteTask(KafkaDataPayload payload, CancellationToken cancellationToken) { var sendTask = new SocketPayloadSendTask(payload, cancellationToken, _log); _sendTaskQueue.Add(sendTask); //StatisticsTracker.QueueNetworkWrite(_endpoint, payload); return(sendTask.Tcp.Task); }
/// <summary> /// Stop watching mouse events /// </summary> public static void Stop() { if (isRunning) { lock (accesslock) { if (mouseHook != null) { mouseHook.MouseAction -= MListener; mouseHook.Stop(); mouseHook = null; } mouseQueue.Add(false); isRunning = false; } } }
public Task <T> EnqueueTask(Func <Task <T> > action, CancellationToken?cancelToken) { var tcs = new TaskCompletionSource <T>(); var item = new AsyncWorkItem <T>(tcs, action, cancelToken); taskQueue.Add(item); return(tcs.Task); }
public static void Stop() { if (_IsRunning) { lock (_Accesslock) { if (_kh != null) { _kh.KeyDown -= new RawKeyEventHandler(KListener); _kh.Stop(); _kh = null; } _kQueue.Add(false); _IsRunning = false; } } }
public void CompletedCollectionShouldShowCompletedTrue() { var collection = new AsyncCollection <int>(); collection.Add(1); Assert.That(collection.IsCompleted, Is.False); collection.CompleteAdding(); Assert.That(collection.IsCompleted, Is.True); }
/// <summary> /// Stop watching /// </summary> public static void Stop() { if (isRunning) { lock (accesslock) { if (keyboardHook != null) { keyboardHook.KeyDown -= new RawKeyEventHandler(KListener); keyboardHook.Stop(); keyboardHook = null; } keyQueue.Add(false); isRunning = false; } } }
/// <summary> /// Start uploading and watching for new replays /// </summary> public async void Start(IMonitor monitor, PreMatchIMonitor prematch_monitor, IAnalyzer analyzer, IUploader uploader) { if (_initialized) { return; } _initialized = true; _uploader = uploader; _analyzer = analyzer; _monitor = monitor; _prematch_monitor = prematch_monitor; var replays = ScanReplays(); Files.AddRange(replays); replays.Where(x => x.UploadStatus == UploadStatus.None).Reverse().Map(x => processingQueue.Add(x)); _monitor.ReplayAdded += async(_, e) => { await EnsureFileAvailable(e.Data, 3000); var replay = new ReplayFile(e.Data); Files.Insert(0, replay); processingQueue.Add(replay); if (PreMatchPage) { _prematch_monitor.Start(); } }; _monitor.Start(); /* * _prematch_monitor.TempBattleLobbyCreated += async (_, e) => { * if (PreMatchPage) { * prematch_id = 0; * _prematch_monitor.Stop(); * Thread.Sleep(1000); * var tmpPath = Path.GetTempFileName(); * await SafeCopy(e.Data, tmpPath, true); * byte[] bytes = System.IO.File.ReadAllBytes(tmpPath); * Replay replay = MpqBattlelobby.Parse(bytes); * await runPreMatch(replay); * } * }; * _prematch_monitor.Start(); */ _analyzer.MinimumBuild = await _uploader.GetMinimumBuild(); for (int i = 0; i < MaxThreads; i++) { Task.Run(UploadLoop).Forget(); } }
public void OnDataAvailableShouldTriggerWhenDataAdded() { var aq = new AsyncCollection<bool>(); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available."); aq.Add(true); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available."); }
public void OnDataAvailableShouldTriggerWhenDataAdded() { var aq = new AsyncCollection <bool>(); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available."); aq.Add(true); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available."); }
public async Task TakeAddMaximum() { //**************************************** var MyCollection = new AsyncCollection <int>(1); //**************************************** var MyTask = MyCollection.Take(); await MyCollection.Add(42); await MyCollection.Add(84); var MyResult = await MyTask; //**************************************** Assert.AreEqual(42, MyResult, "Result was not as expected"); Assert.AreEqual(1, MyCollection.Count, "Count not as expected"); Assert.AreEqual(0, MyCollection.WaitingToAdd, "Waiting adders not as expected"); }
private void ProcessBuffer(object sender, WaveInEventArgs args) { Sample[] values = new Sample[args.Buffer.Length / 2]; for (int i = 0; i < args.BytesRecorded; i += 2) { //short v = (short)((args.Buffer[i + 1] << 8) | args.Buffer[i + 0]); short v = BitConverter.ToInt16(args.Buffer, i); values[i / 2] = new Sample(new[] { (float)v }); } sampleQueue.Add(values); }
public async Task AddMaximumThenComplete() { //**************************************** var MyCollection = new AsyncCollection <int>(1); //**************************************** await MyCollection.Add(42); var MyTask = MyCollection.Add(84); _ = MyCollection.CompleteAdding(); //**************************************** Assert.IsFalse(await MyTask); Assert.AreEqual(1, MyCollection.Count, "Count not as expected"); Assert.IsTrue(MyCollection.IsAddingCompleted, "Adding not completed"); Assert.IsFalse(MyCollection.IsCompleted, "Collection completed"); }
public void OnDataAvailableShouldBlockWhenDataRemoved() { var aq = new AsyncCollection<bool>(); aq.Add(true); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.True, "Task should indicate data available."); bool data; aq.TryTake(out data); Assert.That(aq.OnDataAvailable(CancellationToken.None).IsCompleted, Is.False, "Task should indicate no data available."); }
public async void CollectionShouldReportCorrectBufferCount() { var collection = new AsyncCollection<int>(); var dataTask = collection.TakeAsync(10, TimeSpan.FromHours(5), CancellationToken.None); collection.AddRange(Enumerable.Range(0, 9)); Assert.That(collection.Count, Is.EqualTo(9)); collection.Add(1); var data = await dataTask; Assert.That(data.Count, Is.EqualTo(10)); Assert.That(collection.Count, Is.EqualTo(0)); }
public void TakeAsyncShouldBeThreadSafe() { const int expected = 10; const int max = 100; var exit = false; var collection = new AsyncCollection<int>(); var take1 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); var take2 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); var take3 = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); take1.ContinueWith(t => Console.WriteLine("Take1 done...")); take2.ContinueWith(t => Console.WriteLine("Take2 done...")); take3.ContinueWith(t => Console.WriteLine("Take3 done...")); Task.WhenAll(take1, take2, take3).ContinueWith(x => exit = true); Parallel.ForEach(Enumerable.Range(0, max).ToList(), new ParallelOptions { MaxDegreeOfParallelism = 20 }, x => { while (exit == false) { collection.Add(x); Thread.Sleep(100); } }); Console.WriteLine("Left in collection: {0}", collection.Count); Assert.That(take1.Result.Count, Is.EqualTo(expected)); Assert.That(take2.Result.Count, Is.EqualTo(expected)); Assert.That(take3.Result.Count, Is.EqualTo(expected)); }
public async void TakeAsyncShouldOnlyWaitTimeoutAndReturnWhatItHas() { const int size = 20; var aq = new AsyncCollection<bool>(); Task.Factory.StartNew(() => { //this should take 2000ms to complete for (int i = 0; i < size; i++) { aq.Add(true); Thread.Sleep(100); } }); var result = await aq.TakeAsync(size, TimeSpan.FromMilliseconds(100), CancellationToken.None); Assert.That(result.Count, Is.LessThan(size)); }
public void CompletedCollectionShouldShowCompletedTrue() { var collection = new AsyncCollection<int>(); collection.Add(1); Assert.That(collection.IsCompleted, Is.False); collection.CompleteAdding(); Assert.That(collection.IsCompleted, Is.True); }
public void TakeAsyncShouldPlayNiceWithTPL() { const int expected = 200; const int max = 400; var exit = false; var collection = new AsyncCollection<int>(); var dataTask = collection.TakeAsync(expected, TimeSpan.FromSeconds(100), CancellationToken.None); dataTask.ContinueWith(x => exit = true); Parallel.ForEach(Enumerable.Range(0, max).ToList(), new ParallelOptions { MaxDegreeOfParallelism = 20 }, x => { while (exit == false) { collection.Add(x); Thread.Sleep(100); } }); Console.WriteLine("Left in collection: {0}", collection.Count); Assert.That(dataTask.Result.Count, Is.EqualTo(expected)); }
public async void TakeAsyncShouldReturnEvenWhileMoreDataArrives() { var exit = false; var collection = new AsyncCollection<int>(); var sw = Stopwatch.StartNew(); var dataTask = collection.TakeAsync(10, TimeSpan.FromMilliseconds(5000), CancellationToken.None); var highVolumeAdding = Task.Run(() => { //high volume of data adds while (exit == false) { collection.Add(1); Thread.Sleep(5); } }); Console.WriteLine("Awaiting data..."); await dataTask; Assert.That(dataTask.Result.Count, Is.EqualTo(10)); Assert.That(sw.ElapsedMilliseconds, Is.LessThan(5000)); exit = true; Console.WriteLine("Waiting to unwind test..."); await highVolumeAdding; }
public void CompletedCollectionShouldPreventMoreItemsAdded() { var collection = new AsyncCollection<int>(); collection.Add(1); collection.CompleteAdding(); collection.Add(1); }
public void TestDrainAnApplyNotInInfiniteLoop() { var aq = new AsyncCollection<bool>(); aq.Add(true); var task = Task.Run(() => aq.DrainAndApply(x => aq.Add(x))); Assert.IsTrue(task.Wait(1000)); }