public void ShouldNotReturnNextClaimSequenceUntilBufferHasReserve() { var dependentSequence = new Sequence(Sequencer.InitialCursorValue); Sequence[] dependentSequences = { dependentSequence }; _claimStrategy.SetSequence(_claimStrategy.BufferSize - 1L, dependentSequences); var done = new AtomicBool(false); var beforeLatch = new ManualResetEvent(false); var afterLatch = new ManualResetEvent(false); new Thread( () => { beforeLatch.Set(); Assert.AreEqual(_claimStrategy.BufferSize, _claimStrategy.IncrementAndGet(dependentSequences)); done.Value = true; afterLatch.Set(); }).Start(); beforeLatch.WaitOne(); Thread.Sleep(100); Assert.IsFalse(done.Value); dependentSequence.Value = (dependentSequence.Value + 1L); afterLatch.WaitOne(); Assert.AreEqual(_claimStrategy.BufferSize, _claimStrategy.Sequence); }
public void Exchange_Concurrent() { int accessedTimes = 0; var gate = new object(); var evt = new ManualResetEvent(false); AtomicBool subject = false; Task[] tasks = Enumerable.Repeat( Task.Run( () => { lock (gate) { evt.WaitOne(); } if (subject.Exchange(true)) { Interlocked.Increment(ref accessedTimes); } }), 10) .ToArray(); evt.Set(); Assert.True(Task.WaitAll(tasks, TimeSpan.FromSeconds(10))); Assert.Equal(1, accessedTimes); }
public void Exchange_Twice_SecondFalse() { var subject = new AtomicBool(); Assert.True(subject.Exchange(true)); Assert.False(subject.Exchange(true)); }
public void CaptureContextNoSyncContextTest() { var originalContext = SynchronizationContext.Current; var syncContext = new CustomSyncContext(); try { SynchronizationContext.SetSynchronizationContext(syncContext); var eContext = ExecutionContextHelper.CaptureContextNoSyncContextIfPossible(); Assert.IsNotNull(eContext); AtomicBool isDefaulContext = new AtomicBool(false); var task = Task.Run(() => { SynchronizationContext.SetSynchronizationContext(null); ExecutionContextHelper.RunInContext(eContext, (st) => { isDefaulContext.Value = SynchronizationContext.Current == null; }, null, true); }); task.Wait(); TimingAssert.IsTrue(10000, isDefaulContext, "Default context expected"); } finally { SynchronizationContext.SetSynchronizationContext(originalContext); } }
public void TestCompareAndSetNotSetAtomicBoolWhenActualValueWasNotEqualToTheExpectedValue() { AtomicBool atomicBool = new AtomicBool(); Assert.False(atomicBool.Value); Assert.False(atomicBool.CompareAndSet(true, false)); }
public void AtomicBoolTests_ValueTest() { var atomicBool = new AtomicBool(true); Assert.IsTrue(atomicBool.Value); atomicBool.Value = false; Assert.IsFalse(atomicBool.Value); }
public void TestWasFalse() { var boolean = new AtomicBool(); if (boolean.WasFalse()) { if (boolean.WasFalse()) { Assert.Fail("AtomicBool should be true until SetFalse is called"); } boolean.SetFalse(); if (boolean.WasFalse()) { Assert.Pass(); } else { Assert.Fail("AtomicBool should be reset by calling SetFalse"); } } else { Assert.Fail("AtomicBool should be false when initialized"); } }
public static int Read(this S7Client plc, int area, int[] address, AtomicBool value) { int result; int wordIndex = address[0]; int bitIndex = address[1]; byte[] buffer = new byte[1]; switch (area) { case S7Consts.S7AreaMK: result = plc.MBRead(wordIndex, 1, buffer); break; case S7Consts.S7AreaPA: result = plc.ABRead(wordIndex, 1, buffer); break; default: result = S7Consts.errCliInvalidBlockType; break; } value.Value = Sharp7.S7.GetBitAt(buffer, 0, bitIndex); return(result); }
public void TestSetValueToFalse() { AtomicBool atomicBool = new AtomicBool(true); Assert.True(atomicBool.Value); atomicBool.Set(false); Assert.False(atomicBool.Value); }
public void TestCompareAndSetAtomicBoolToFalse() { AtomicBool atomicBool = new AtomicBool(true); Assert.True(atomicBool.Value); Assert.True(atomicBool.CompareAndSet(true, false)); Assert.False(atomicBool.Value); }
public async Task TestManyThreads() { var boolean = new AtomicBool(); var threads = await Simultaneously.Run(100, boolean.WasFalse); threads.Where(x => x).ShouldHaveSingleItem(); }
/// <summary> /// Constructs a <see cref="ResolutionScopeBase"/>. /// </summary> public ResolutionScopeBase() { this.disposed = new AtomicBool(); this.rootItem = DisposableItem.Empty; this.rootFinalizableItem = FinalizableItem.Empty; this.scopedItems = new ConcurrentTree <object, object>(); this.scopedInstances = new ConcurrentTree <Type, object>(); }
private StashMoq(MockRepository repository, MockBehavior behavior, bool verifyAll) : base(new StashboxContainer(config => config.WithUnknownTypeResolution())) { this.repository = repository; this.behavior = behavior; this.verifyAll = verifyAll; this.disposed = new AtomicBool(); base.Container.RegisterResolver(new MoqResolver(this.repository, base.RequestedTypes)); }
public void TestAtomicBool() { var b = AtomicBool.From(true); Assert.True(b.Value); Assert.True(b.CompareExchange(false, true)); Assert.False(b.Value); Assert.True(b.Exchange(true)); Assert.True(b.Value); Assert.True(b); }
private CompilerContext(DelegateTarget target, Expression[] definedVariables, Expression[] storedExpressions, Expression[] capturedArguments, KeyValue <LambdaExpression, Expression[]>[] nestedLambdas, CapturedArgumentsHolder capturedArgumentsHolder, bool isNestedLambda, bool hasCapturedVariablesArgumentConstructed) { this.hasCapturedVariablesArgumentConstructed = new AtomicBool(hasCapturedVariablesArgumentConstructed); this.Target = target; this.DefinedVariables = definedVariables; this.StoredExpressions = storedExpressions; this.CapturedArgumentsHolder = capturedArgumentsHolder; this.IsNestedLambda = isNestedLambda; this.CapturedArguments = capturedArguments; this.NestedLambdas = nestedLambdas; }
public void AtomicBoolTests_CompareExchangeTest() { var atomicBool = new AtomicBool(); var counter = 0; var iterations = 100; Parallel.For(0, iterations, (i) => { while (!atomicBool.CompareExchange(false, true)) ; ++counter; atomicBool.Value = false; }); Assert.AreEqual(iterations, counter); }
internal StashboxContainer(IStashboxContainer parentContainer, IContainerExtensionManager containerExtensionManager, IResolverSelector resolverSelector) { this.disposed = new AtomicBool(); this.ParentContainer = parentContainer; this.containerExtensionManager = containerExtensionManager; this.resolverSelector = resolverSelector; this.registrationRepository = new RegistrationRepository(); this.ContainerContext = new ContainerContext(this.registrationRepository, new DelegateRepository(), this, new ResolutionStrategy(this.resolverSelector), parentContainer.ContainerContext.ContainerConfigurator, parentContainer.ContainerContext.DecoratorRepository); this.activationContext = new Resolution.ActivationContext(this.ContainerContext, this.resolverSelector, this); this.containerExtensionManager.ReinitalizeExtensions(this.ContainerContext); this.expressionBuilder = new ExpressionBuilder(this.ContainerContext, this.containerExtensionManager); this.objectBuilderSelector = new ObjectBuilderSelector(this.ContainerContext, this.expressionBuilder); this.ServiceRegistrator = new ServiceRegistrator(this.ContainerContext, this.containerExtensionManager, this.objectBuilderSelector); }
public void TestTaskSchedulerSetted() { using (DynamicThreadPool testInst = new DynamicThreadPool(0, Environment.ProcessorCount, -1, "name", false, new DynamicThreadPoolOptions() { UseOwnTaskScheduler = true, UseOwnSyncContext = true })) { AtomicBool isPropperSceduller = new AtomicBool(false); testInst.Run(() => { isPropperSceduller.Value = TaskScheduler.Current == testInst.TaskScheduler; }); TimingAssert.IsTrue(10000, isPropperSceduller, "isPropperSceduller"); testInst.Dispose(true, true, false); } }
private ResolutionScope(IResolverSelector resolverSelector, IServiceRegistrator serviceRegistrator, IExpressionBuilder expressionBuilder, IContainerContext containerContext, AvlTreeKeyValue <object, Func <IResolutionScope, object> >[] serviceDelegateCache, AvlTreeKeyValue <object, Func <IResolutionScope, Delegate> >[] factoryDelegates, object name) { this.disposed = new AtomicBool(); this.rootItem = DisposableItem.Empty; this.rootFinalizableItem = FinalizableItem.Empty; this.scopedItems = AvlTreeKeyValue <object, object> .Empty; this.scopedInstances = AvlTreeKeyValue <Type, object> .Empty; this.resolverSelector = resolverSelector; this.serviceRegistrator = serviceRegistrator; this.expressionBuilder = expressionBuilder; this.containerContext = containerContext; this.Name = name; this.serviceDelegates = serviceDelegateCache; this.factoryDelegates = factoryDelegates; this.indexBound = this.serviceDelegates.Length - 1; }
/// <summary> /// Constructs a <see cref="StashboxContainer"/> /// </summary> public StashboxContainer(Action <IContainerConfigurator> config = null) { this.disposed = new AtomicBool(); this.containerExtensionManager = new BuildExtensionManager(); this.resolverSelector = new ResolverSelector(); var configurator = new ContainerConfigurator(); config?.Invoke(configurator); this.registrationRepository = new RegistrationRepository(); this.ContainerContext = new ContainerContext(this.registrationRepository, new DelegateRepository(), this, new ResolutionStrategy(this.resolverSelector), configurator, new DecoratorRepository()); this.activationContext = new Resolution.ActivationContext(this.ContainerContext, this.resolverSelector, this); this.expressionBuilder = new ExpressionBuilder(this.ContainerContext, this.containerExtensionManager); this.objectBuilderSelector = new ObjectBuilderSelector(this.ContainerContext, this.expressionBuilder); this.ServiceRegistrator = new ServiceRegistrator(this.ContainerContext, this.containerExtensionManager, this.objectBuilderSelector); this.RegisterResolvers(); }
public void SetTaskSchedulerAndExecuteEntryTest() { var sched = new TestTaskScheduler(); int val = 0; AtomicBool taskSchedullerSetted = new AtomicBool(false); Task tsk = null; tsk = new Task(() => { taskSchedullerSetted.Value = TaskScheduler.Current == sched; Interlocked.Increment(ref val); }); TaskHelper.SetTaskScheduler(tsk, sched); TaskHelper.ExecuteTaskEntry(tsk); TimingAssert.IsTrue(10000, taskSchedullerSetted, "taskSchedullerSetted"); }
internal StashboxContainer(IContainerExtensionManager containerExtensionManager, IResolverSelector resolverSelector, IContainerConfigurator containerConfigurator, IDecoratorRepository decoratorRepository, Action <IContainerConfigurator> config = null) { this.disposed = new AtomicBool(); this.containerExtensionManager = containerExtensionManager; this.resolverSelector = resolverSelector; config?.Invoke(containerConfigurator); this.ContainerContext = new ContainerContext(this.registrationRepository, this, new ResolutionStrategy(this.resolverSelector), containerConfigurator, decoratorRepository); var expressionBuilder = new ExpressionBuilder(this.containerExtensionManager); this.objectBuilderSelector = new ObjectBuilderSelector(expressionBuilder); this.ServiceRegistrator = new ServiceRegistrator(this.ContainerContext, this.containerExtensionManager, this.objectBuilderSelector); this.RootScope = new ResolutionScope(this.resolverSelector, this.ServiceRegistrator, expressionBuilder, this.ContainerContext); this.rootResolver = (IDependencyResolver)this.RootScope; }
public void RegisterWithoutECTest() { var originalContext = SynchronizationContext.Current; var syncContext = new CustomSyncContext(); try { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; AtomicBool isNoExecutionContext = new AtomicBool(false); using (CancellationTokenHelper.RegisterWithoutECIfPossible(token, (st) => { isNoExecutionContext.Value = SynchronizationContext.Current == null; }, null)) { Barrier barrier = new Barrier(2); Barrier barrier2 = new Barrier(2); Task.Run(() => { barrier.SignalAndWait(); barrier2.SignalAndWait(); tokenSource.Cancel(); }); barrier.SignalAndWait(); SynchronizationContext.SetSynchronizationContext(syncContext); barrier2.SignalAndWait(); TimingAssert.IsTrue(10000, isNoExecutionContext, "isNoExecutionContext"); } } finally { SynchronizationContext.SetSynchronizationContext(originalContext); } }
/// <summary> /// Create a stage program. /// </summary> /// <param name="clock">Clock for timing</param> /// <param name="stageProvider">Stage provider that providing stages</param> /// <param name="preferPreloaded">Prefer pre-loaded stages if possible</param> public StageProgram([NotNull] IClock clock, [NotNull] IStageProvider stageProvider, bool preferPreloaded = true) { if (stageProvider == null) { throw new ArgumentNullException(nameof(stageProvider)); } OriginalClock = clock ?? throw new ArgumentNullException(nameof(clock)); FreezableClock = new FreezableClock(clock.As(TimeUnit.Millisecond)); FreezableClock.Frozen += (sender, e) => _pausedEvent.Set(); FreezableClock.Unfrozen += (sender, e) => _pausedEvent.Reset(); _stageProvider = preferPreloaded && stageProvider.TryPreload(out var preloaded) ? preloaded : stageProvider; _cyclicExecutor = new AsyncCyclicExecutor("StageProgram Worker", DoWork, true, ThreadPriority.Highest, null, StoppingAction.Abort); _cyclicExecutor.Starting += (sender, e) => { CurrentStage = null; _pausedEvent.Set(); StartTime = Time; _nextUpdateTime = 0; }; _cyclicExecutor.Started += (sender, e) => Started?.Invoke(this, EventArgs.Empty); _cyclicExecutor.Stopped += (sender, e) => Stopped?.Invoke(this, EventArgs.Empty); _stageSkipped = new AtomicBool(false); _pausedEvent = new ManualResetEvent(false); }
public void TestSyncContextSetted() { using (DynamicThreadPool testInst = new DynamicThreadPool(0, Environment.ProcessorCount, -1, "name", false, new DynamicThreadPoolOptions() { UseOwnTaskScheduler = true, UseOwnSyncContext = true })) { AtomicBool isPropperSyncContext = new AtomicBool(false); testInst.Run(() => { if (SynchronizationContext.Current != null) { SynchronizationContext.Current.Post((st) => { isPropperSyncContext.Value = testInst.IsThreadPoolThread; }, null); } }); TimingAssert.IsTrue(10000, isPropperSyncContext, "isPropperSyncContext"); testInst.Dispose(true, true, false); } }
public void TestNoSyncContextAndTaskSchedullerWhenNotConfigurated() { using (DynamicThreadPool testInst = new DynamicThreadPool(0, Environment.ProcessorCount, -1, "name", false, new DynamicThreadPoolOptions() { UseOwnTaskScheduler = false, UseOwnSyncContext = false })) { var defSyncContext = SynchronizationContext.Current; var defTaskScheduller = TaskScheduler.Current; AtomicBool isDefaultSyncContext = new AtomicBool(false); AtomicBool isDefaultTaskScheduller = new AtomicBool(false); testInst.Run(() => { isDefaultSyncContext.Value = SynchronizationContext.Current == defSyncContext; isDefaultTaskScheduller.Value = TaskScheduler.Current == defTaskScheduller; }); TimingAssert.IsTrue(10000, isDefaultSyncContext, "isDefaultSyncContext"); TimingAssert.IsTrue(10000, isDefaultTaskScheduller, "isDefaultTaskScheduller"); testInst.Dispose(true, true, false); } }
// ====================== private void ValidateCountTest(DiskQueue <int> queue, CommonSegmentFactory <int> factory, int elemCount) { Barrier bar = new Barrier(2); CancellationTokenSource cancelled = new CancellationTokenSource(); List <int> takenElems = new List <int>(elemCount + 1); AtomicBool needSync = new AtomicBool(); Action addAction = () => { int curElem = 0; Random rnd = new Random(Environment.TickCount + Thread.CurrentThread.ManagedThreadId); bar.SignalAndWait(); while (curElem < elemCount) { bool itemAdded = true; if (rnd.Next(100) == 0) { queue.AddForced(curElem); } else if (needSync.Value) { itemAdded = queue.TryAdd(curElem); } else { queue.Add(curElem); } if (rnd.Next(100) == 0) { Thread.Yield(); } SpinWaitHelper.SpinWait(rnd.Next(12)); if (itemAdded) { curElem++; } Assert.IsTrue(itemAdded || needSync.Value); if (curElem % 1000 == 0) { needSync.Value = true; } if (needSync.Value && bar.ParticipantsRemaining == 1) { Assert.AreEqual(factory.SumCountFromAllocated(), queue.Count); needSync.Value = false; bar.SignalAndWait(); } } cancelled.Cancel(); }; Action takeAction = () => { Random rnd = new Random(Environment.TickCount + Thread.CurrentThread.ManagedThreadId); bar.SignalAndWait(); try { while (!cancelled.IsCancellationRequested) { takenElems.Add(queue.Take(cancelled.Token)); if (rnd.Next(100) == 0) { Thread.Yield(); } SpinWaitHelper.SpinWait(rnd.Next(12)); if (needSync.Value) { bar.SignalAndWait(cancelled.Token); } } } catch (OperationCanceledException) { } int item = 0; while (queue.TryTake(out item)) { takenElems.Add(item); } }; var sw = System.Diagnostics.Stopwatch.StartNew(); Task addTask = Task.Factory.StartNew(addAction, TaskCreationOptions.LongRunning); Task takeTask = Task.Factory.StartNew(takeAction, TaskCreationOptions.LongRunning); Task.WaitAll(addTask, takeTask); Assert.AreEqual(elemCount, takenElems.Count); for (int i = 0; i < takenElems.Count; i++) { if (i != takenElems[i]) { Assert.AreEqual(i, takenElems[i], $"i != takenElems[i], nextItem = {takenElems[i + 1]}"); } } }
public virtual bool Init(ServerExecuteType executeType, string version, string name = null) { Running = new AtomicBool(); Stopped = new AtomicBool(); ExecuteType = executeType; Name = string.IsNullOrEmpty(name) == true?Process.GetCurrentProcess().ProcessName : name; Version = version; ModuleName = Name; CreateLogger(); Logger.Info("Init"); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); if (LoadServerConfig() == false) { if (ExecuteType == ServerExecuteType.Console) { Console.ReadKey(); } return(false); } TheadPoolEx.SetMinMaxThreads( m_ServerConfig.MinWorkerThreads == 0 ? Environment.ProcessorCount : m_ServerConfig.MinWorkerThreads, m_ServerConfig.MaxWorkerThreads == 0 ? Environment.ProcessorCount * 2: m_ServerConfig.MaxWorkerThreads, m_ServerConfig.MinCompletionPortThreads == 0 ? Environment.ProcessorCount : m_ServerConfig.MinCompletionPortThreads, m_ServerConfig.MaxCompletionPortThreads == 0 ? Environment.ProcessorCount * 2 : m_ServerConfig.MaxCompletionPortThreads); m_Sessions = new ConcurrentDictionary <long, Session>(); m_Listeners = new List <Listener>(); try { int bufferSize = m_ServerConfig.ReceiveBufferSize; if (bufferSize <= 0) { bufferSize = 1024 * 4; } // Send, Recv m_BufferManager = new BufferManager(bufferSize * m_ServerConfig.MaxConnectionNumber * 2, bufferSize); try { m_BufferManager.InitBuffer(); int[] poolSizes = new int[] { 4096, 16, 128, 256, 1024 }; m_PooledBufferManager = new PooledBufferManager(poolSizes); { SocketAsyncEventArgs socketEventArg; var socketArgsList = new List <SocketAsyncEventArgs>(m_ServerConfig.MaxConnectionNumber); for (int i = 0; i < m_ServerConfig.MaxConnectionNumber; i++) { socketEventArg = new SocketAsyncEventArgs(); socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(CompletedReceive); m_BufferManager.SetBuffer(socketEventArg); socketArgsList.Add(socketEventArg); } m_RecvSAEAPool = new ConcurrentStack <SocketAsyncEventArgs>(socketArgsList); } { SocketAsyncEventArgs socketEventArg; var socketArgsList = new List <SocketAsyncEventArgs>(m_ServerConfig.MaxConnectionNumber); for (int i = 0; i < m_ServerConfig.MaxConnectionNumber; i++) { socketEventArg = new SocketAsyncEventArgs(); socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(CompletedSend); //m_BufferManager.SetBuffer(socketEventArg); // Send할때 별도의 풀을 사용할거라서 socketEventArg.SetBuffer(null, 0, 0); socketArgsList.Add(socketEventArg); } m_SendSAEAPool = new ConcurrentStack <SocketAsyncEventArgs>(socketArgsList); } } catch (Exception e) { Logger.Error("메모리 부족! 최대 접속 허용 인원 설정을 낮추세요", e); if (ExecuteType == ServerExecuteType.Console) { Console.ReadKey(); } return(false); } m_Updater = new TimerThread(Update, null, 1); return(true); } catch (Exception e) { Logger.Error("Server.Init", e); if (ExecuteType == ServerExecuteType.Console) { Console.ReadKey(); } return(false); } }
public void TestAtomicBoolDefaultCtor() { var ab = new AtomicBool(); Assert.False(ab.Value); }
internal CircuitBreakerBot(Bot innerBot, CircuitBreakerConfiguration configuration, CircuitBreakerStrategy strategy) : base(innerBot, configuration) { this.strategy = strategy; this.executionBarrier = new AtomicBool(); }
/// <summary> /// Constructs a <see cref="MockingBase"/>. /// </summary> /// <param name="container"></param> protected MockingBase(IStashboxContainer container) { this.Container = container; this.RequestedTypes = new HashSet <Type>(); this.disposed = new AtomicBool(); }