private static void ConfigurationThreadTest(Action<DbConfigurationManager> beforeThreads, Action<DbConfigurationManager> inThreads) { for (var i = 0; i < 30; i++) { var configurationBag = new ConcurrentBag<DbConfiguration>(); var manager = new DbConfigurationManager(new DbConfigurationLoader(), new DbConfigurationFinder()); beforeThreads(manager); ExecuteInParallel( () => { inThreads(manager); configurationBag.Add(manager.GetConfiguration()); }); Assert.Equal(20, configurationBag.Count); Assert.True(configurationBag.All(c => manager.GetConfiguration() == c)); } }
/// <summary> /// Create the min amount of connections, if the pool is empty /// </summary> private void MaybeCreateCorePool() { var coreConnections = Configuration.GetPoolingOptions(ProtocolVersion).GetCoreConnectionsPerHost(HostDistance); if (_connections == null || _connections.All(c => c.IsClosed)) { lock (_poolCreationLock) { if (_connections != null && !_connections.All(c => c.IsClosed)) { return; } _connections = new ConcurrentBag <Connection>(); while (_connections.Count < coreConnections) { try { _connections.Add(CreateConnection()); } catch { if (_connections.Count == 0) { //Leave the pool to its previous state _connections = null; } throw; } } } } }
public void main(string[] args) { worker.DoWork += worker_DoWork; worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.RunWorkerAsync(); bool run = true; for (int i = 2; i < args.Length; i++) { names.Add(new CharacterFind { CharacterName = args[i] }); } while (run) { CycleThings(int.Parse(args[1]), args[0]); if (names.All(x => x.Found)) { run = false; } Thread.Sleep(60000); } }
/// <summary> /// Initialize the cluster stream /// </summary> /// <param name="keySequence">Key sequence instance</param> /// <param name="carrierStreams">Carrier streams to initialized with</param> /// <remarks> /// Key Step Lengths(KSL) /// Key Step Length Size(KSLS) /// Writable Carrier Stream Length(WCSL) /// WCSL / Sum(KSL) * KSLS + WCSL % Sum(KSL) = Length /// </remarks> public override void Initialize(IKeySequence keySequence, IEnumerable <ICarrierStream> carrierStreams) { _keySequence = keySequence; long currentStart = 0; _carrierStreams = new ConcurrentBag <StreamSegment>( carrierStreams.Select(cs => { long closureCurrentStart = currentStart; long end = closureCurrentStart + cs.Length - 1; currentStart = end + 1; return(new StreamSegment { Start = closureCurrentStart, End = end, CarrierStream = cs }); })); _canRead = _carrierStreams.All(s => s.CarrierStream.CanRead); _canSeek = _carrierStreams.All(s => s.CarrierStream.CanSeek); _canWrite = _carrierStreams.All(s => s.CarrierStream.CanWrite); long carrierSumLength = _carrierStreams.Sum(s => s.CarrierStream.Length); _maxLength = carrierSumLength / _keySequence.TotalStepSum * _keySequence.Length + carrierSumLength % _keySequence.TotalStepSum; _length = _maxLength; _logger.Info(h => h("Initialize: KeySequence Length: {0}, Stream Lengh = {1}", _keySequence.Length, _length)); }
public void AddUser(User user) { if (instance.All(u => u.Key != user.Id)) { instance.Add(new KeyValuePair <int, User>(user.Id, user)); } }
public static async Task <bool> AreAllQueuesEmptyAsync(TimeSpan waitTime) { var start = DateTime.UtcNow; while (DateTime.UtcNow.Subtract(start) > waitTime) { if (AllQueues.All(x => x.Count == 0)) { return(true); } await Task.Delay(100); } return(AllQueues.All(x => x.Count == 0)); }
public void TestFinalizesAfterClientIsDisposed() { ConcurrentBag <WeakReference> weakRef = new ConcurrentBag <WeakReference>(); Action <Action <IIgniteClient> > act = startTx => { var client = GetClient(); weakRef.Add(new WeakReference(client)); var cache = GetTransactionalCache(client); startTx(client); cache[42] = 42; client.Dispose(); }; Action <IIgniteClient>[] txStarts = { // ReSharper disable once ObjectCreationAsStatement client => new TransactionScope(), client => client.GetTransactions().TxStart() }; foreach (var txStart in txStarts) { var tasks = Enumerable.Range(0, 3) .Select(i => Task.Factory.StartNew(() => act(txStart), TaskCreationOptions.LongRunning)) .ToArray(); Task.WaitAll(tasks); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsFalse(weakRef.All(wr => wr.IsAlive)); } }
public async Task <bool> ParallelCallAsyncTask <T1, T2>(List <T1> dataList, List <T2> helperList, Func <IEnumerable <T1>, T2, Task <bool> > funcAsync) { if (!dataList.Any()) { return(true); } int dataSize = dataList.Count; int helpSize = helperList.Count; int chunkSize = (dataSize + helpSize - 1) / helpSize; IEnumerable <IEnumerable <T1> > enumerables = dataList.Chunk(chunkSize); var results = new ConcurrentBag <bool>(); IEnumerable <Task> tasks = enumerables.Select(async(batch, index) => { results.Add(await funcAsync(batch, helperList[index])); }); await Task.WhenAll(tasks); return(results.All(c => c)); }
//[DataRow("lang_ar_text.archive")] //[DataRow("lang_cs_text.archive")] //[DataRow("lang_de_text.archive")] //[DataRow("lang_en_text.archive")] //[DataRow("lang_en_voice.archive")] //[DataRow("lang_es-es_text.archive")] //[DataRow("lang_es-mx_text.archive")] //[DataRow("lang_fr_text.archive")] //[DataRow("lang_hu_text.archive")] //[DataRow("lang_it_text.archive")] //[DataRow("lang_ja_text.archive")] //[DataRow("lang_ko_text.archive")] //[DataRow("lang_pl_text.archive")] //[DataRow("lang_pt_text.archive")] //[DataRow("lang_ru_text.archive")] //[DataRow("lang_th_text.archive")] //[DataRow("lang_tr_text.archive")] //[DataRow("lang_zh-cn_text.archive")] //[DataRow("lang_zh-tw_text.archive")] public void Test_Unbundle(string archivename) { var resultDir = Path.Combine(Environment.CurrentDirectory, s_testResultsDirectory); Directory.CreateDirectory(resultDir); var results = new ConcurrentBag <ArchiveTestResult>(); var archiveFullName = Path.Combine(s_gameDirectoryPath, "archive", "pc", "content", archivename); var archive = s_bm.Archives.Lookup(archiveFullName).Value as Archive; Parallel.ForEach(archive.Files, keyvalue => { var(hash, _) = keyvalue; try { using (var ms = new MemoryStream()) { ModTools.ExtractSingleToStream(archive, hash, ms); } results.Add(new ArchiveTestResult() { ArchiveName = archivename, Hash = hash.ToString(), Success = true }); } catch (Exception e) { results.Add(new ArchiveTestResult() { ArchiveName = archivename, Hash = hash.ToString(), Success = false, ExceptionType = e.GetType(), Message = $"{e.Message}" }); } }); var totalCount = archive.Files.Count; // Check success var successCount = results.Count(r => r.Success); var sb = new StringBuilder(); sb.AppendLine($"Successfully unbundled: {successCount} / {totalCount} ({(int)(successCount / (double)totalCount * 100)}%)"); var success = results.All(r => r.Success); if (success) { return; } var msg = $"Successful Writes: {successCount} / {totalCount}. "; Assert.Fail(msg); }
public override bool Execute() { // Determine all valid parameters var verificationParamsDict = new Dictionary <string, string>(); foreach (var param in DafnyVerificationParams) { var keyVal = GetSplitParam(param); verificationParamsDict[keyVal[0]] = keyVal.Length == 2 ? keyVal[1] : ""; } foreach (var requiredParam in REQUIRED_PARAMS) { if (!verificationParamsDict.ContainsKey(requiredParam)) { throw new ArgumentException(String.Format("{0} required for verification", requiredParam)); } } // Determine if the verification task should be performed in parallel ParallelOptions options = new ParallelOptions(); int jobCount; if (Jobs != null && int.TryParse(Jobs, out jobCount)) { options.MaxDegreeOfParallelism = jobCount; } // Verify all files ConcurrentBag <bool> results = new ConcurrentBag <bool>(); Parallel.ForEach(DafnySourceFiles, options, file => { results.Add(VerifyDafnyFile(file, verificationParamsDict)); }); return(results.All(x => x)); }
public void Instance_ThreadSafe() { using (var gate = new Barrier(5)) { var result = new ConcurrentBag<AnyConstructorFinder>(); Action test = () => { gate.SignalAndWait(20); var instance = AnyConstructorFinder.Instance; Thread.MemoryBarrier(); result.Add(instance); }; var cycleState = Parallel.For(0, 200, new ParallelOptions { MaxDegreeOfParallelism = 15 }, x => { test(); }) ; while (!cycleState.IsCompleted) { Thread.Sleep(100); } Assert.IsTrue(result.All(x => x != null)); Assert.IsTrue(result.Distinct().Count() == 1); } }
public void RegisterErrorMessage(LocalizedString message) { if (_errorMessages != null && _errorMessages.All(m => m.TextHint != message.TextHint)) { _errorMessages.Add(message); } }
public async Task only_return_events_that_satisfy_a_given_event_regex() { var filter = Filter.EventType.Regex(new Regex(@"^.*BEv.*$")); var foundEvents = new ConcurrentBag <ResolvedEvent>(); using (var store = BuildConnection(_node)) { await store.ConnectAsync(); var appeared = new TaskCompletionSource <bool>(); using (await store.FilteredSubscribeToAllAsync(false, filter, (s, e) => { foundEvents.Add(e); if (foundEvents.Count == 5) { appeared.TrySetResult(true); } return(Task.CompletedTask); }, (s, p) => Task.CompletedTask, 100)) { await _conn.AppendToStreamAsync("stream-a", ExpectedVersion.NoStream, _testEvents.EvenEvents()); await _conn.AppendToStreamAsync("stream-b", ExpectedVersion.NoStream, _testEvents.OddEvents()); await appeared.Task.WithTimeout(Timeout); Assert.True(foundEvents.All(e => e.Event.EventType == "BEvent")); } } }
public bool ParallelCall <T1, T2>(List <T1> dataList, List <T2> helperList, Func <IEnumerable <T1>, T2, bool> func) { if (!dataList.Any()) { return(true); } int dataSize = dataList.Count; int helpSize = helperList.Count; int chunkSize = (dataSize + helpSize - 1) / helpSize; var enumerables = dataList.Chunk(chunkSize).Select((c, index) => new TempData <T1, T2>() { SourceList = c, Helper = helperList[index] }); var results = new ConcurrentBag <bool>(); Parallel.ForEach(enumerables, data => { results.Add(func(data.SourceList, data.Helper)); }); return(results.All(c => c)); }
private static void Main(string[] args) { // http://holsee.com/tag/c/ var go = DateTime.Now.AddSeconds(2); //TEST 1 //var tasks = (from i in Enumerable.Range(0,100) // select makeThread(go)).ToArray(); //Task.WaitAll(tasks); //var collectionClasses = tasks.Select(x => x.Result).ToArray(); ConcurrentBag <CollectionClass> collectionClasses = new ConcurrentBag <CollectionClass>(); Parallel.For(0, 10, i => { var c = ThreadWork(go); collectionClasses.Add(c); }); //Console.WriteLine("{0} Items",collectionClasses.Count); Console.WriteLine(); Console.WriteLine("============================="); var cCheck = collectionClasses.First(); if (collectionClasses.All(c => Object.ReferenceEquals(c, cCheck))) { Console.WriteLine("All Good on object reference"); } else { Console.WriteLine("Fail object reference"); } if (collectionClasses.All(x => x.TotalNumbers == cCheck.TotalNumbers)) { Console.WriteLine("All Good on Total numbers"); } else { Console.WriteLine("Fail total numbers"); } }
/// <summary> /// Determines if the queue is empty after waiting the specified waitTime. /// Returns true or false if the underlying queues are empty. /// </summary> /// <param name="waitTime">The length of time the method should block before giving up waiting for it to empty.</param> /// <returns>True if the queue is empty, false if there are still items waiting to be written.</returns> public static bool AreAllQueuesEmpty(TimeSpan waitTime) { var start = DateTime.UtcNow; var then = DateTime.UtcNow; while (start.Add(waitTime) > then) { if (_allQueues.All(x => x.Count == 0)) { return(true); } Thread.Sleep(100); then = DateTime.UtcNow; } return(_allQueues.All(x => x.Count == 0)); }
public void CachingTest() { List <int> trackIds = new List <int>(32); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { for (var i = 0; i < trackIds.Capacity; i++) { trackIds.Add(new AudioTrack() { Name = "SomeTrack" }.TrackId); } transaction.Complete(); } ConcurrentBag <Pair <int> > results = new ConcurrentBag <Pair <int> >(); var source = trackIds.Select(t => new { PId = t, Bag = results }); Parallel.ForEach( source, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (sourceItem, state, currentItteration) => { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var trackToLock = session.Query.All <AudioTrack>().FirstOrDefault(t => t.TrackId == sourceItem.PId); EventHandler <DbCommandEventArgs> handler = (sender, args) => { sourceItem.Bag.Add(new Pair <int>(sourceItem.PId, (int)args.Command.Parameters[0].Value)); }; session.Events.DbCommandExecuting += handler; if (trackToLock != null) { trackToLock.Lock(LockMode.Update, LockBehavior.Wait); } session.Events.DbCommandExecuting -= handler; } }); try { Assert.That(results.Count, Is.EqualTo(trackIds.Capacity)); Assert.That(results.All(t => t.First == t.Second), Is.True); } finally { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { session.Remove(session.Query.All <AudioTrack>().Where(t => t.TrackId.In(trackIds))); transaction.Complete(); } } }
protected void Track(params TableEntity[] entities) { foreach (var entity in entities) { if (TrackedEntities.All(e => e.RowKey != entity.RowKey)) { TrackedEntities.Add(entity); } } }
public void AddressUidExtension_should_always_report_same_value() { var values = new ConcurrentBag<int>(); var parallelOps = 1000; var loop = Parallel.For(0, parallelOps, i => { values.Add(AddressUidExtension.Uid(Sys)); }); SpinWait.SpinUntil(() => loop.IsCompleted); Assert.True(values.All(x => x == AddressUidExtension.Uid(Sys))); }
public void Save(MiniProfiler profiler) { if (Bag.Count() > Limit) { Reset(); } if (Bag.All(p => p.Id != profiler.Id)) { Bag.Add(profiler); } }
internal static void StartNextTestRun() { if (TestRuns.All(t => t.RunStatus != RunStatus.Started)) { var testRun = TestRuns.FirstOrDefault(t => t.RunStatus == RunStatus.Waiting); if (testRun != null) { testRun.Start(); testRun.TestRunIdleTimer.Elapsed += TestRunIdleTimer_Elapsed; } } }
public void RevealDecryptedBytesAsync_FromMultipleThreads_DoesNotCorruptData() { // arrange sut var sut = GetSut(); var expected = GetTestBytes(sut.BlockSizeInBytes); sut.InitializeAsync(expected.CopyToNewArray()); // arrange threads const int totalThreads = 6; const int totalCountPerThread = 100; var collection = new ConcurrentBag <byte[]>(); var threads = new Thread[totalThreads]; var random = new Random(); for (var i = 0; i < totalThreads; i++) { var threadId = i; threads[i] = new Thread(() => { // act var count = 0; while (count < totalCountPerThread) { Console.WriteLine($"Thread {threadId} is running for {count} time."); using (var firstSession = sut.RevealDecryptedBytesAsync().Result) { var actual = firstSession.PlainBytes.CopyToNewArray(); collection.Add(actual); var sleepMs = random.Next(0, 100); Console.WriteLine($"Thread {threadId} is sleeping for {sleepMs} ms."); Thread.Sleep(sleepMs); } count++; } Console.WriteLine($"Thread {threadId} is completed"); }); } // run foreach (var thread in threads) { thread.Start(); } foreach (var thread in threads) { thread.Join(); } // assert Console.WriteLine($"Total revealed results in the bag: {collection.Count}"); Assert.True(collection.All(bytes => expected.SequenceEqual(bytes))); }
public void AddressUidExtension_should_always_report_same_value() { var values = new ConcurrentBag <int>(); var parallelOps = 1000; var loop = Parallel.For(0, parallelOps, i => { values.Add(AddressUidExtension.Uid(Sys)); }); SpinWait.SpinUntil(() => loop.IsCompleted); Assert.True(values.All(x => x == AddressUidExtension.Uid(Sys))); }
private void assertCulture(string name) { var cultures = new ConcurrentBag <CultureInfo>(); AddStep("query cultures", () => { host.DrawThread.Scheduler.Add(() => cultures.Add(Thread.CurrentThread.CurrentCulture)); host.UpdateThread.Scheduler.Add(() => cultures.Add(Thread.CurrentThread.CurrentCulture)); }); AddUntilStep("wait for query", () => cultures.Count == 3); AddAssert($"culture is {name}", () => cultures.All(c => c.Name == name)); }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag <DbProviderServices>(); var resolver = new DefaultProviderServicesResolver(); ExecuteInParallel(() => bag.Add(resolver.GetService <DbProviderServices>("System.Data.SqlClient"))); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => SqlProviderServices.Instance == c)); } }
public void FastAtomicLazy_must_be_threadsafe_AnyRef() { for (var c = 0; c < 100000; c++) // try this 100000 times { var values = new ConcurrentBag <string>(); var fal = new FastLazy <string>(() => Faker.Generators.Strings.GenerateAlphaNumericString()); var result = Parallel.For(0, 1000, i => values.Add(fal.Value)); // 1000 concurrent operations SpinWait.SpinUntil(() => result.IsCompleted); var value = values.First(); Assert.NotNull(value); Assert.True(values.All(x => x.Equals(value))); } }
public void Should_Concurrently_Load_A_Session_And_Unlock_It_Afterwards() { SessionDatabase.CreateSession(Constants.FullSessionId, ShortData); var store = new SqlSessionStateStore(Constants.ConnectionString, Constants.SessionTimeout); var results = new ConcurrentBag<bool>(); for (var i = 0; i < 20; i++) ThreadPool.QueueUserWorkItem( x => results.Add((store.Load(_sessionId) ?? new byte[] {}).SequenceEqual(ShortData))); while (results.Count < 20) Thread.Sleep(100); results.All(x => x).ShouldBeTrue(); }
public void FastAtomicLazy_must_be_threadsafe() { for (var c = 0; c < 100000; c++) // try this 100000 times { var values = new ConcurrentBag <int>(); var fal = new FastLazy <int>(() => new Random().Next(1, Int32.MaxValue)); var result = Parallel.For(0, 1000, i => values.Add(fal.Value)); // 1000 concurrent operations SpinWait.SpinUntil(() => result.IsCompleted); var value = values.First(); Assert.NotEqual(0, value); Assert.True(values.All(x => x.Equals(value))); } }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag<DbProviderServices>(); var resolver = new DefaultProviderServicesResolver(); ExecuteInParallel(() => bag.Add(resolver.GetService<DbProviderServices>("System.Data.SqlClient"))); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => SqlProviderServices.Instance == c)); } }
/// <summary> /// Update the primeCache to full digit (e.g. limit is 47 -> update to exponent of 2 -> 100) /// </summary> /// <param name="limit">number limit to update</param> private static void UpdatePrimesCache(long limit) { var exponentValue = limit.ToString().Length; // get the all numbers within the same number of digits (e.g. 50 -> 100, 450 -> 1000) limit = (long)Math.Pow(10, exponentValue); var primeLimit = Math.Sqrt(limit); if (_primes.Count == 0) { // initial 200 primes var intArray = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199 }; _primes.UnionWith(intArray); } var maxCurrentNumber = _primes.Max; // if limit is less then our maxNumber in cache, finish if (maxCurrentNumber > limit) { return; } var leftSide = new ConcurrentBag <int>(); var rightSide = new ConcurrentBag <int>(); // get the range of numbers to evaluate a new primes var range = Enumerable.Range(maxCurrentNumber, (int)(limit - maxCurrentNumber) + 1) .AsParallel() .Where(n => !_primes.Any(a => n % a == 0)); // split range set into 2: leftSide (all numbers which are less than Math.sqrt(limit) and right side all other numbers in the range) foreach (var num in range) { if (num <= primeLimit) { leftSide.Add(num); } else { rightSide.Add(num); } } // remove the not prime numbers from right side, based on the number from the left side var cleanedRightSide = rightSide.Where(a => leftSide.All(b => a % b != 0)).AsParallel(); // add to cache _primes.UnionWith(leftSide); _primes.UnionWith(cleanedRightSide); }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag <IPilkington>(); var karl = new Mock <IPilkington>().Object; var resolver = new SingletonDependencyResolver <IPilkington>(karl, "Karl"); ExecuteInParallel(() => bag.Add(resolver.GetService <IPilkington>("Karl"))); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => karl == c)); } }
private WorkerProgressModel GetProgressModelForCurrentWorker(int workerHash) { if (_workerProgress.All(e => e.WorkedId != workerHash)) { _workerProgress.Add(new WorkerProgressModel { WorkedId = workerHash, CompletedBatches = 0, CurrentProgress = 0 }); } return(_workerProgress.First(e => e.WorkedId == workerHash)); }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag<IPilkington>(); var karl = new Karl(); var resolver = new TransientDependencyResolver<IPilkington>(() => karl, "Karl"); ExecuteInParallel(() => bag.Add(resolver.GetService<IPilkington>("Karl"))); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => karl == c)); } }
public void TestSaveUpdatesAutoIncrementingField() { //---------------Set up test pack------------------- ClassDef.ClassDefs.Clear(); TestAutoInc.LoadClassDefWithAutoIncrementingID(); var newIds = new ConcurrentBag<int?>(); //---------------Execute Test ---------------------- Parallel.For(0, 1000, i => { //---------------Set up test pack------------------- var bo = new TestAutoInc(); bo.SetPropertyValue("testfield", "testing 123"); //---------------Assert Precondition---------------- Assert.IsFalse(bo.TestAutoIncID.HasValue); //---------------Execute Test ---------------------- bo.Save(); //---------------Test Result ----------------------- newIds.Add(bo.TestAutoIncID); }); //---------------Test Result ----------------------- Assert.IsTrue(newIds.All(i => i.HasValue)); Assert.IsTrue(newIds.All(i => i > 0)); Assert.That(newIds.Distinct().Count(), Is.EqualTo(1000), "Every generated ID must be unique"); }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag <AttributeProvider>(); var resolver = new RootDependencyResolver(); ExecuteInParallel(() => bag.Add(resolver.GetService <AttributeProvider>())); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => c.GetType() == typeof(AttributeProvider))); } }
public void Dispose() { Logger.Log(Level.Debug, "disposing thread pool"); _disposed = true; Logger.Log(Level.Debug, "waiting for pending workers"); SpinWait.SpinUntil(() => _workers.All(w => w.State == State.Stopped)); Logger.Log(Level.Debug, "all workers finished their job"); while (_workers.TryTake(out Worker worker)) { } Logger.Log(Level.Debug, "workers destroyed"); _queue.Dispose(); Logger.Log(Level.Debug, "thread pool disposed"); }
public void only_return_events_that_are_not_system_events() { var filter = Filter.ExcludeSystemEvents; var foundEvents = new ConcurrentBag <ResolvedEvent>(); var appeared = new CountdownEvent(20); Subscribe(filter, foundEvents, appeared); if (!appeared.Wait(Timeout)) { Assert.Fail("Appeared countdown event timed out."); } Assert.True(foundEvents.All(e => !e.Event.EventType.StartsWith("$"))); }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag<IPilkington>(); var karl1 = new Mock<IPilkington>().Object; var resolver = new CompositeResolver<IDbDependencyResolver, IDbDependencyResolver>( new SingletonDependencyResolver<IPilkington>(karl1), new SingletonDependencyResolver<IPilkington>(new Mock<IPilkington>().Object)); ExecuteInParallel(() => bag.Add(resolver.GetService<IPilkington>())); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => karl1 == c)); } }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag<AttributeProvider>(); var resolver = new RootDependencyResolver(); resolver.AddDefaultResolver(new SingletonDependencyResolver<AttributeProvider>(new AttributeProvider())); resolver.AddDefaultResolver(new SingletonDependencyResolver<AttributeProvider>(new AttributeProvider())); ExecuteInParallel(() => bag.Add(resolver.GetService<AttributeProvider>())); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => c.GetType() == typeof(AttributeProvider))); } }
static void Main(string[] args) { var stopWatch = new Stopwatch(); using (var eventStore = WireupEventStore()) { Console.Write("Inserting {0} AggregateRoots with {1} commits each", AmountOfRoots, AmountOfCommitsPerRoot); stopWatch.Start(); byte[] payload = new byte[80]; var resetEvents = new ConcurrentBag<ManualResetEventSlim>(); for (int i = 0; i < AmountOfRoots; ++i) { if (i % (AmountOfRoots / 100) == 0) { Thread.Sleep(500); Console.Write("."); } var resetEvent = new ManualResetEventSlim(); resetEvents.Add(resetEvent); ThreadPool.QueueUserWorkItem(x => { var currentRoot = Guid.NewGuid(); for (int commits = 0; commits < AmountOfCommitsPerRoot; ++commits) { using (var stream = eventStore.OpenStream(currentRoot, 0, int.MaxValue)) { stream.Add(new EventMessage() { Body = payload }); stream.CommitChanges(Guid.NewGuid()); } } ((ManualResetEventSlim)x).Set(); }, resetEvent); } while (!resetEvents.All(x => x.IsSet)) { Thread.Sleep(100); } stopWatch.Stop(); Console.WriteLine("done in {0} ms.", stopWatch.ElapsedMilliseconds); Console.ReadKey(); } }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag<IDatabaseInitializer<FakeContext1>>(); var resolver = new DatabaseInitializerResolver(); var initializer = new Mock<IDatabaseInitializer<FakeContext1>>().Object; ExecuteInParallel( () => { resolver.SetInitializer(typeof(FakeContext1), initializer); bag.Add(resolver.GetService<IDatabaseInitializer<FakeContext1>>()); }); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => initializer == c)); } }
public void Model_hash_can_be_calculated_from_multiple_threads_using_a_single_DbCompiledModel() { var hashes = new ConcurrentBag<string>(); ExecuteInParallel( () => { using (var context = new SimpleModelContext()) { #pragma warning disable 612,618 var hash = EdmMetadata.TryGetModelHash(context); #pragma warning restore 612,618 Assert.NotNull(hash); hashes.Add(hash); } }); Assert.True(hashes.All(h => hashes.First() == h)); }
public void EDMX_can_be_written_from_multiple_threads_using_a_single_DbCompiledModel() { var edmxs = new ConcurrentBag<string>(); ExecuteInParallel( () => { var edmxBuilder = new StringBuilder(); using (var context = new SimpleModelContext()) { // Cached DbCompiledModel will be used each time EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilder)); } var edmx = edmxBuilder.ToString(); Assert.True(edmx.Contains("EntitySet Name=\"Products\"")); Assert.True(edmx.Contains("EntitySet Name=\"Categories\"")); edmxs.Add(edmx); }); Assert.True(edmxs.All(m => edmxs.First() == m)); }
public void Should_Return_Session_State_For_All_Classic_Concurent_Requests() { var counts = new ConcurrentBag<int>(); var session = Common.GetClassic("command=add&key=state&value=CO&datatype=String"); for (var i = 0; i < 20; i++) ThreadPool.QueueUserWorkItem(x => counts.Add(session.GetClassic().Data.Count)); while (counts.Count < 20) Thread.Sleep(100); counts.All(x => x == 1).ShouldBeTrue(); }
public void GetService_can_be_accessed_from_multiple_threads_concurrently() { var appConfig = new AppConfig( CreateEmptyConfig().AddDefaultConnectionFactory(typeof(FakeConnectionFactory).AssemblyQualifiedName)); for (var i = 0; i < 30; i++) { var bag = new ConcurrentBag<IDbConnectionFactory>(); var resolver = new AppConfigDependencyResolver(appConfig); ExecuteInParallel(() => bag.Add(resolver.GetService<IDbConnectionFactory>())); Assert.Equal(20, bag.Count); Assert.True(bag.All(c => resolver.GetService<IDbConnectionFactory>() == c)); } }