/// <summary> /// Creates a new unlimited collection over the given producer consumer collection /// </summary> /// <param name="collection">The collection to block over</param> public AsyncCollection(IProducerConsumerCollection <T> collection) { _Collection = collection ?? throw new ArgumentNullException(nameof(collection)); Capacity = int.MaxValue; _UsedSlots = new AsyncCounter(collection.Count); }
internal DelegateSet <TResource> SetDelegatesToDefaultsWhereNull ( Selector <TResource> selector = null, Inserter <TResource> inserter = null, Updater <TResource> updater = null, Deleter <TResource> deleter = null, Authenticator <TResource> authenticator = null, Counter <TResource> counter = null, Validator <TResource> validator = null, AsyncSelector <TResource> asyncSelector = null, AsyncInserter <TResource> asyncInserter = null, AsyncUpdater <TResource> asyncUpdater = null, AsyncDeleter <TResource> asyncDeleter = null, AsyncAuthenticator <TResource> asyncAuthenticator = null, AsyncCounter <TResource> asyncCounter = null ) { SyncSelector ??= selector; SyncInserter ??= inserter; SyncUpdater ??= updater; SyncDeleter ??= deleter; SyncAuthenticator ??= authenticator; SyncCounter ??= counter; Validator ??= validator; AsyncSelector ??= asyncSelector; AsyncInserter ??= asyncInserter; AsyncUpdater ??= asyncUpdater; AsyncDeleter ??= asyncDeleter; AsyncAuthenticator ??= asyncAuthenticator; AsyncCounter ??= asyncCounter; return(this); }
public async Task Executor_should_execute_tasks_until_disposal() { var task1Name = "task1"; var task2Name = "task2"; var countdown1 = new AsyncCountdown(task1Name, 10); var counter1 = new AsyncCounter(); var countdown2 = new AsyncCountdown(task2Name, 10); var counter2 = new AsyncCounter(); using (var executor = ContinuousTaskExecutor <string> .StartExecutor(Mock.Of <ITimeCoordinator>())) { Assert.True(executor.TryRegisterTaskFor(task1Name, (item, token) => StartTaskAsync(countdown1, counter1, token))); await countdown1.WaitAsync(_testTimeout); Assert.True(executor.TryRegisterTaskFor(task2Name, (item, token) => StartTaskAsync(countdown2, counter2, token))); await countdown2.WaitAsync(_testTimeout); // check that task 1 still works await countdown1.ResetTo(10).WaitAsync(_testTimeout); } var expected1 = counter1.Value; var expected2 = counter2.Value; await Task.Delay(200); Assert.Equal(expected1, counter1.Value); Assert.Equal(expected2, counter2.Value); }
public async Task DecrementMultiCancel() { //**************************************** var MyCounter = new AsyncCounter(); //**************************************** using (var MySource = new CancellationTokenSource()) { var MyTask1 = MyCounter.Decrement(MySource.Token); var MyTask2 = MyCounter.Decrement(); Assert.IsFalse(MyTask1.IsCompleted, "Decremented too early"); Assert.IsFalse(MyTask2.IsCompleted, "Decremented too early"); MySource.Cancel(); Assert.IsTrue(MyTask1.IsCanceled, "Wait not cancelled"); Assert.IsFalse(MyTask2.IsCanceled, "Wait cancelled"); MyCounter.Increment(); await MyTask2; } //**************************************** Assert.AreEqual(0, MyCounter.CurrentCount, "Counter not decremented"); Assert.AreEqual(0, MyCounter.WaitingCount, "Tasks unexpectedly waiting"); }
public void DecrementCancel() { //**************************************** var MyCounter = new AsyncCounter(); ValueTask MyTask; //**************************************** using (var MySource = new CancellationTokenSource()) { MyTask = MyCounter.Decrement(MySource.Token); Assert.IsFalse(MyTask.IsCompleted, "Decremented too early"); MySource.Cancel(); Assert.IsTrue(MyTask.IsCanceled, "Wait not cancelled"); } // Since there are no waiters that aren't cancelled, this should succeed immediately MyCounter.Increment(); //**************************************** Assert.AreEqual(1, MyCounter.CurrentCount, "Counter still decremented"); Assert.AreEqual(0, MyCounter.WaitingCount, "Tasks unexpectedly waiting"); }
/// <summary> /// Creates a new collection over the given producer consumer collection /// </summary> /// <param name="collection">The collection to block over</param> /// <param name="capacity">The maximum number of items in the queue</param> public AsyncCollection(IProducerConsumerCollection <T> collection, int capacity) { if (capacity <= 0) { throw new ArgumentException("Capacity is invalid"); } _Collection = collection ?? throw new ArgumentNullException(nameof(collection)); Capacity = capacity; _UsedSlots = new AsyncCounter(collection.Count); _FreeSlots = new AsyncCounter(capacity); }
public void Add() { //**************************************** var MyCounter = new AsyncCounter(); //**************************************** MyCounter.Add(10); //**************************************** Assert.AreEqual(10, MyCounter.CurrentCount, "Counter not incremented"); Assert.AreEqual(0, MyCounter.WaitingCount, "Tasks unexpectedly waiting"); }
public void DecrementInitial() { //**************************************** var MyCounter = new AsyncCounter(1); //**************************************** var MyTask = MyCounter.Decrement(); //**************************************** Assert.IsTrue(MyTask.IsCompleted, "Still waiting to decrement"); Assert.AreEqual(0, MyCounter.CurrentCount, "Counter not decremented"); Assert.AreEqual(0, MyCounter.WaitingCount, "Tasks unexpectedly waiting"); }
public void DisposeDecrement() { //**************************************** var MyLock = new AsyncCounter(); //**************************************** MyLock.DisposeAsync(); Assert.ThrowsAsync <ObjectDisposedException>(() => MyLock.Decrement().AsTask()); //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyLock.CurrentCount, "Count not zero"); }
public async Task DisposeTryDecrementAsync() { //**************************************** var MyLock = new AsyncCounter(); //**************************************** _ = MyLock.DisposeAsync(); Assert.IsFalse(await MyLock.TryDecrementAsync()); //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyLock.CurrentCount, "Count not zero"); }
public void IncrementDispose() { //**************************************** var MyLock = new AsyncCounter(); //**************************************** MyLock.Increment(); var DisposeTask = MyLock.DisposeAsync(); Assert.IsFalse(DisposeTask.IsCompleted, "Dispose completed early"); //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Waiter still registered"); Assert.AreEqual(1, MyLock.CurrentCount, "Count not one"); }
public async Task StackBlow() { //**************************************** var MyLock = new AsyncCounter(); Task ResultTask; Task[] Results; //**************************************** Results = Enumerable.Range(1, 40000).Select( async count => { await MyLock.Decrement(); MyLock.Increment(); }).ToArray(); ResultTask = Results[^ 1].ContinueWith(task => System.Diagnostics.Debug.WriteLine("Done to " + new System.Diagnostics.StackTrace(false).FrameCount.ToString()), TaskContinuationOptions.ExecuteSynchronously);
public void DecrementTimeoutNone() { //**************************************** var MyCounter = new AsyncCounter(); //**************************************** MyCounter.Increment(); var MyTask = MyCounter.Decrement(TimeSpan.FromMilliseconds(50)); //**************************************** Assert.IsTrue(MyTask.IsCompleted, "Still waiting to decrement"); Assert.AreEqual(0, MyCounter.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyCounter.CurrentCount, "Count not zero"); }
public async Task DecrementTimeoutDelayed() { //**************************************** var MyCounter = new AsyncCounter(); //**************************************** var MyTask = MyCounter.Decrement(TimeSpan.FromMilliseconds(50)); MyCounter.Increment(); //**************************************** await MyTask; //**************************************** Assert.AreEqual(0, MyCounter.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyCounter.CurrentCount, "Count not zero"); }
public async Task DecrementToZeroAdd() { //**************************************** var MyCounter = new AsyncCounter(); //**************************************** var MyTask = MyCounter.DecrementToZero(); Assert.IsFalse(MyTask.IsCompleted, "Decremented too early"); MyCounter.Add(10); //**************************************** Assert.AreEqual(10, await MyTask); Assert.AreEqual(0, MyCounter.CurrentCount, "Counter not decremented"); Assert.AreEqual(0, MyCounter.WaitingCount, "Tasks unexpectedly waiting"); }
public void IncrementDisposeTryDecrement() { //**************************************** var MyLock = new AsyncCounter(); //**************************************** MyLock.Increment(); _ = MyLock.DisposeAsync(); Assert.IsTrue(MyLock.TryDecrement()); Assert.IsFalse(MyLock.TryDecrement()); //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyLock.CurrentCount, "Count not zero"); }
public void HideDruid(int wait) { Journal.Clear(); Game.CurrentGame.CurrentPlayer.SwitchWarmode(); StandardSkill usedSkill = StandardSkill.Hiding; SkillValue hidingSV = SkillsHelper.GetSkillValue("Hiding"); SkillValue stealthSV = SkillsHelper.GetSkillValue("Stealth"); if (stealthSV.RealValue > hidingSV.RealValue) { usedSkill = StandardSkill.Stealth; } Game.RunScript(3000); UO.UseSkill(usedSkill); AsyncCounter counter = new AsyncCounter(); counter.PrefixText = "Vracecka: "; counter.HighlightTime = 1500; counter.Step = 400; counter.StopMessage = "You can't seem to hide here,You have hidden yourself well,You can't do much in your"; counter.StopMethod = IsHidden; counter.Run(); if (World.Player.Backpack.AllItems.FindType(0x1B17, 0x0493).Exist) { Game.Wait(wait); UO.UseType(0x1B17, 0x0493); } else { World.Player.PrintMessage("Nemas artefakt!"); } }
public async Task Exchange_should_try_download_list_of_endpoints_periodically_until_disposal() { var countdown = new AsyncCountdown(nameof(IHealthMonitorExchangeClient.RegisterMonitorsAsync), 10); var counter = new AsyncCounter(); SetupDefaultRegisterEndpointsMock(); _exchangeClient.Setup(c => c.GetEndpointIdentitiesAsync(EndpointMetadata.DefaultMonitorTag, It.IsAny <CancellationToken>())) .Returns(() => _awaitableFactory.Throw <EndpointIdentity[]>(new InvalidOperationException()).WithCountdown(countdown).WithCounter(counter).RunAsync()); using (CreateExchange(new DataExchangeConfig(100, 10, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(1), EndpointMetadata.DefaultMonitorTag))) await countdown.WaitAsync(TestMaxWaitTime); var capturedCalls = counter.Value; Assert.True(capturedCalls > 0, "capturedCalls>0"); await Task.Delay(PostRunDelay); Assert.Equal(capturedCalls, counter.Value); }
public async Task Exchange_should_retry_uploading_supported_monitor_types_until_disposal() { var countdown = new AsyncCountdown(nameof(IHealthMonitorExchangeClient.RegisterMonitorsAsync), 10); var counter = new AsyncCounter(); _exchangeClient .Setup(c => c.RegisterMonitorsAsync(It.IsAny <IEnumerable <string> >(), It.IsAny <CancellationToken>())) .Returns(() => _awaitableFactory.Throw(new InvalidOperationException()).WithCountdown(countdown).WithCounter(counter).RunAsync()); SetupDefaultEndpointIdentitiesMock(); using (CreateExchange(new DataExchangeConfig(100, 10, TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(1)))) await countdown.WaitAsync(TestMaxWaitTime); var capturedCalls = counter.Value; Assert.True(capturedCalls > 0, "capturedCalls>0"); await Task.Delay(PostRunDelay); Assert.Equal(capturedCalls, counter.Value); }
public async Task Manager_should_delete_old_stats() { const int expectedRepeats = 3; var age = TimeSpan.FromHours(1); var utcNow = DateTime.UtcNow; var asyncCountdown = new AsyncCountdown("delete old stats", expectedRepeats); var asyncCounter = new AsyncCounter(); var monitorSettings = new Mock <IMonitorSettings>(); monitorSettings.Setup(s => s.StatsHistoryMaxAge).Returns(age); var timeCoordinator = new Mock <ITimeCoordinator>(); timeCoordinator.Setup(c => c.UtcNow).Returns(utcNow); var endpointMetricsCoordinator = new Mock <IEndpointMetricsForwarderCoordinator>(); var repository = new Mock <IEndpointStatsRepository>(); repository.Setup(r => r.DeleteStatisticsOlderThan(utcNow - age, It.IsAny <int>())).Returns(() => { asyncCountdown.Decrement(); asyncCounter.Increment(); const int deletedItemsCount = 127; return(asyncCounter.Value >= expectedRepeats ? 0 : deletedItemsCount); }); using (new EndpointStatsManager(repository.Object, monitorSettings.Object, timeCoordinator.Object, endpointMetricsCoordinator.Object)) await asyncCountdown.WaitAsync(MaxTestTime); await Task.Delay(TimeSpan.FromMilliseconds(500)); //it should stop calling cleanup when there are no more items to be cleaned Assert.Equal(expectedRepeats, asyncCounter.Value); }
public void DisposeIncrement() { //**************************************** var MyLock = new AsyncCounter(); //**************************************** MyLock.DisposeAsync(); try { MyLock.Increment(); Assert.Fail("Should never reach this point"); } catch (ObjectDisposedException) { } //**************************************** Assert.AreEqual(0, MyLock.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyLock.CurrentCount, "Count not zero"); }
public async Task DecrementTimeout() { //**************************************** var MyCounter = new AsyncCounter(); //**************************************** try { await MyCounter.Decrement(TimeSpan.FromMilliseconds(10)); Assert.Fail("Task did not cancel"); } catch (TimeoutException) { } //**************************************** //MyCounter.Dispose(); //Assert.AreEqual(0, MyCounter.WaitingCount, "Waiter still registered"); Assert.AreEqual(0, MyCounter.CurrentCount, "Count not zero"); }
public void Initalize() { researchCounter = new AsyncCounter(); IsResearchDone = !(ResearchTime > 0); if (!IsResearchDone) { researchCounter.Start(ResearchTime); } upgCounter = new AsyncCounter(); IsUpgradeDone = !(UpgradeTime > 0); if (!IsUpgradeDone) { upgCounter.Start(UpgradeTime); } trainingCounter = new AsyncCounter(); IsTrainingDone = !(TrainingTime > 0); if (!IsTrainingDone) { trainingCounter.Start(TrainingTime); } }
public void Rewind() { ItemHelper.EnsureContainer(World.Player.Backpack); UOItem uOItem = World.Player.Backpack.Items.FindType(GreeziArtefakt.Graphic); if (uOItem.Exist) { Journal.Clear(); uOItem.Use(); if (Journal.WaitForText(true, 500, "You used Rewind")) { Game.PrintMessage("Rewin Start"); AsyncCounter counter = new AsyncCounter(); counter.PrefixText = "Rewind: "; counter.PrintType = "Game"; counter.ForceCounter = true; counter.HighlightTime = 3100; counter.HighlightColor = 0x055A; counter.Step = 500; counter.MaxTries = 12; counter.StopMessage = "You was ported back in time"; counter.StopMethod = Hiding.IsHidden; counter.RunComplete += Counter_RunComplete; counter.Run(); } } else { World.Player.PrintMessage("Nemas artefakt", MessageType.Warning); } }
public void HideInBattle(int highlightTime, ushort highlightColor, int counterStep) { if (World.Player.Layers[Layer.LeftHand].Graphic == 0x0A15)//lantern { UOItem shield = new UOItem(Serial.Invalid); List <UOItem> items = new List <UOItem>(); items.AddRange(World.Player.Backpack.Items); foreach (UOItem item in items) { foreach (Graphic g in ItemLibrary.Shields.GraphicArray) { if (item.Graphic == g && (!shield.Exist || shield.Graphic != 0x1B76)) { shield = item; } } } if (shield.Exist) { shield.Use(); } else { World.Player.Layers[Layer.LeftHand].Move(1, World.Player.Backpack, 100, 30); } Game.Wait(250); } Journal.Clear(); SkillValue hidingSV = SkillsHelper.GetSkillValue("Hiding"); SkillValue stealthSV = SkillsHelper.GetSkillValue("Stealth"); StandardSkill usedSkill = StandardSkill.Hiding; if (stealthSV.RealValue > hidingSV.RealValue) { usedSkill = StandardSkill.Stealth; } AsyncCounter counter = new AsyncCounter(); counter.PrefixText = ""; if (highlightTime > 0) { counter.HighlightTime = highlightTime; } if (highlightColor > 0) { counter.HighlightColor = highlightColor; } Game.RunScript(3000); UO.UseSkill(usedSkill); if (Journal.WaitForText(true, 200, "You are preoccupied with thoughts of battle")) { Game.CurrentGame.CurrentPlayer.SwitchWarmode(); World.Player.PrintMessage("[ Preoccupied ]", MessageType.Warning); Game.Wait(250); if (World.Player.Hits < World.Player.Strenght) { UO.BandageSelf(); } else { UO.UseSkill(StandardSkill.Meditation); } //else if (World.Player.Mana > 4) // UO.Cast(StandardSpell.MagicArrow, World.Player.Serial); } else { counter.Step = counterStep; counter.StopMessage = "You can't seem to hide here,You have hidden yourself well"; counter.StopMethod = IsHidden; counter.Run(); } //You are preoccupied with thoughts of battle //Game.RunScript(3500); //Hiding.HideRunning = true; //if (needAction) //{ // World.Player.PrintMessage("[ HID Action ]", MessageType.Warning); // if (World.Player.Hits < World.Player.Strenght) // UO.BandageSelf(); // else if (World.Player.Mana > 4) // UO.Cast(StandardSpell.MagicArrow, World.Player.Serial); //} //Game.Wait(250); //UO.UseSkill(usedSkill); //Game.Wait(50); }
private Task StartTaskAsync(AsyncCountdown countdown, AsyncCounter counter, CancellationToken token) { return(StartTaskAsync(token, c => c.WithCountdown(countdown).WithCounter(counter))); }
public void Hide(int highlightTime, ushort highlightColor, int counterStep, Graphic dropItemGraphic, UOColor dropItemColor) { Journal.Clear(); Game.CurrentGame.CurrentPlayer.SwitchWarmode(); StandardSkill usedSkill = StandardSkill.Hiding; SkillValue hidingSV = SkillsHelper.GetSkillValue("Hiding"); SkillValue stealthSV = SkillsHelper.GetSkillValue("Stealth"); if (stealthSV.RealValue > hidingSV.RealValue) { usedSkill = StandardSkill.Stealth; } if (World.Player.Layers[Layer.LeftHand].Graphic == 0x0A15)//lantern { UOItem shield = new UOItem(Serial.Invalid); List <UOItem> items = new List <UOItem>(); items.AddRange(World.Player.Backpack.Items); foreach (UOItem item in items) { foreach (Graphic g in ItemLibrary.Shields.GraphicArray) { if (item.Graphic == g && (!shield.Exist || shield.Graphic != 0x1B76)) { shield = item; } } } if (shield.Exist) { shield.Use(); } else { World.Player.Layers[Layer.LeftHand].Move(1, World.Player.Backpack, 100, 30); } Game.Wait(150); } Game.RunScript(3000); AsyncCounter counter = new AsyncCounter(); counter.PrefixText = ""; if (highlightTime > 0) { counter.HighlightTime = highlightTime; } if (highlightColor > 0) { counter.HighlightColor = highlightColor; } if (!dropItemGraphic.IsInvariant) { int origDistance = World.FindDistance; World.FindDistance = 3; UOItem item = World.Ground.FindType(dropItemGraphic, dropItemColor); if (item.Exist && item.Distance <= 3) { item.Move(item.Amount, World.Player.Backpack); } World.FindDistance = origDistance; } Hiding.HideRunning = true; UO.UseSkill(usedSkill); Game.Wait(50); if (!dropItemGraphic.IsInvariant && World.Player.Backpack.AllItems.FindType(dropItemGraphic, dropItemColor).Exist) { DropItemGraphic = dropItemGraphic; DropItemColor = dropItemColor; counter.RunComplete += Counter_RunComplete; } counter.Step = counterStep; counter.StopMessage = "You can't seem to hide here,You have hidden yourself well"; counter.StopMethod = IsHidden; counter.Run(); }
public void HideRay(int highlightTime, ushort highlightColor, int counterStep) { Journal.Clear(); StandardSkill usedSkill = StandardSkill.Hiding; SkillValue hidingSV = SkillsHelper.GetSkillValue("Hiding"); SkillValue stealthSV = SkillsHelper.GetSkillValue("Stealth"); if (stealthSV.RealValue > hidingSV.RealValue) { usedSkill = StandardSkill.Stealth; } if (World.Player.Layers[Layer.LeftHand].Graphic == 0x0A15)//lantern { UOItem shield = new UOItem(Serial.Invalid); List <UOItem> items = new List <UOItem>(); items.AddRange(World.Player.Backpack.Items); foreach (UOItem item in items) { foreach (Graphic g in ItemLibrary.Shields.GraphicArray) { if (item.Graphic == g && (!shield.Exist || shield.Graphic != 0x1B76)) { shield = item; } } } if (shield.Exist) { shield.Use(); } else { World.Player.Layers[Layer.LeftHand].Move(1, World.Player.Backpack, 100, 30); } Game.Wait(250); } Game.RunScript(3000); AsyncCounter counter = new AsyncCounter(); counter.PrefixText = ""; if (highlightTime > 0) { counter.HighlightTime = highlightTime; } if (highlightColor > 0) { counter.HighlightColor = highlightColor; } Hiding.HideRunning = true; UO.BandageSelf(); Game.Wait(100); UO.UseSkill(usedSkill); Game.Wait(50); counter.Step = counterStep; counter.StopMessage = "You can't seem to hide here,You have hidden yourself well"; counter.StopMethod = IsHidden; counter.Run(); }
public void Hide(int highlightTime, ushort highlightColor, int counterStep) { Journal.Clear(); Game.CurrentGame.CurrentPlayer.SwitchWarmode(); StandardSkill usedSkill = StandardSkill.Hiding; SkillValue hidingSV = SkillsHelper.GetSkillValue("Hiding"); SkillValue stealthSV = SkillsHelper.GetSkillValue("Stealth"); if (stealthSV.RealValue > hidingSV.RealValue) { usedSkill = StandardSkill.Stealth; } if (World.Player.Layers[Layer.LeftHand].Graphic == 0x0A15)//lantern { UOItem shield = new UOItem(Serial.Invalid); List <UOItem> items = new List <UOItem>(); items.AddRange(World.Player.Backpack.Items); foreach (UOItem item in items) { foreach (Graphic g in ItemLibrary.Shields.GraphicArray) { if (item.Graphic == g && (!shield.Exist || shield.Graphic != 0x1B76)) { shield = item; } } } if (shield.Exist) { shield.Use(); } else { World.Player.Layers[Layer.LeftHand].Move(1, World.Player.Backpack, 100, 30); } Game.Wait(150); } //UOItem whWepna = World.Player.FindColor(0x0B60, new Graphic[] { 0x143A, 0x1404, 0x0F62, 0x13B9, 0x0F5C, 0x1438, 0x0F60, 0x0F5E, 0x0E87 }); //Nightstone zbran u WJ //if (whWepna.Exist && whWepna.Layer != Layer.LeftHand && whWepna.Layer != Layer.RightHand) //{ // whWepna.Use(); // Game.Wait(150); // Targeting.ResetTarget(); //} Game.RunScript(3000); AsyncCounter counter = new AsyncCounter(); counter.PrefixText = ""; if (highlightTime > 0) { counter.HighlightTime = highlightTime; } if (highlightColor > 0) { counter.HighlightColor = highlightColor; } Hiding.HideRunning = true; UO.UseSkill(usedSkill); Game.Wait(50); counter.Step = counterStep; counter.StopMessage = "You can't seem to hide here,You have hidden yourself well"; counter.StopMethod = IsHidden; counter.Run(); }