public async Task MailKit_NonSSL() { using (DefaultServer server = new DefaultServer(false, StandardSmtpPort.AssignAutomatically)) { ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>(); server.MessageReceivedEventHandler += (o, ea) => { messages.Add(ea.Message); return(Task.CompletedTask); }; server.Start(); await this.SendMessage_MailKit_Async(server, "*****@*****.**").WithTimeout("sending message").ConfigureAwait(false); Assert.Single(messages); Assert.Equal("*****@*****.**", messages.First().From); } }
private bool IsNewCorrId(string corrId) { lock (_lockObject) { if (_uuids.Contains(corrId)) { return(false); } if (_uuids.Count >= MAX_UUIDS) { _uuids.First().Remove(0); } _uuids.Add(corrId); return(true); } }
public async Task MailKit_ImplicitTLS() { using (DefaultServer server = new DefaultServer(false, (int)StandardSmtpPort.AssignAutomatically, CreateSelfSignedCertificate(), null)) { ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>(); server.MessageReceivedEventHandler += (o, ea) => { messages.Add(ea.Message); return(Task.CompletedTask); }; server.Start(); await this.SendMessage_MailKit_Async(server, "*****@*****.**", secureSocketOptions : MailKit.Security.SecureSocketOptions.SslOnConnect).WithTimeout("sending message").ConfigureAwait(false); Assert.Single(messages); Assert.Equal("*****@*****.**", messages.First().From); } }
public void TestStoreApi() { var updates = new ConcurrentBag <AppEntity>(); using (var client = new HttpRetryClient(200)) { var steamApps = MissingUpdater.GetAllSteamApps(client).Result; var portalApp = steamApps.FirstOrDefault(app => app.appid == 400 && String.Equals(app.name, "Portal", StringComparison.Ordinal)); Assert.IsNotNull(portalApp, "Could not find Portal in the steam library: {0}", String.Join(", ", steamApps.Select(a => String.Format(CultureInfo.InvariantCulture, "{0}/{1}", a.appid, a.name)))); SteamStoreHelper.GetStoreInformationUpdates(new[] { new BasicStoreInfo(portalApp.appid, portalApp.name, null) }, client, updates).Wait(); } Assert.AreEqual(1, updates.Count, "Expected exactly one update for requested app (Portal)"); var portal = updates.First(); Assert.IsTrue(portal.IsGame, "Portal is not classified as a game"); Assert.IsFalse(portal.IsDlc, "Portal is classified as a DLC"); Assert.IsFalse(portal.IsMod, "Portal is classified as a mod"); Assert.IsTrue(portal.Categories.Contains("Single-player", StringComparer.OrdinalIgnoreCase), "Portal is not classified as single-player: {0}", portal.CategoriesFlat); Assert.AreEqual("Valve", portal.Developers.SingleOrDefault(), "Valve are not listed as the sole developers of Portal: {0}", portal.DevelopersFlat); Assert.AreEqual("Valve", portal.Publishers.SingleOrDefault(), "Valve are not listed as the sole publishers of Portal: {0}", portal.PublishersFlat); Assert.IsTrue(portal.Genres.Contains("Action", StringComparer.OrdinalIgnoreCase), "Portal is not classified as an action game: {0}", portal.GenresFlat); Assert.IsTrue(portal.MetacriticScore > 85, "Portal is scored too low on Metacritic: {0}", portal.MetacriticScore); Assert.IsTrue(portal.Platforms.HasFlag(Common.Entities.Platforms.Windows) && portal.Platforms.HasFlag(Common.Entities.Platforms.Linux) && portal.Platforms.HasFlag(Common.Entities.Platforms.Mac), "Portal is not listed as supported on Windows, Mac, and Linux: {0}", portal.Platforms); Assert.AreEqual(new DateTime(2007, 10, 10), portal.ReleaseDate, "Portal release date is incorrect"); }
public static void ExecuteOnNewThreads(int threadsCount, Action <int> action, int timeoutMilliseconds = 10000) { var actionsExecutedCount = 0; var exceptions = new ConcurrentBag <Exception>(); var threads = Enumerable.Range(0, threadsCount).Select(i => { var thread = new Thread(_ => { try { action(i); Interlocked.Increment(ref actionsExecutedCount); } catch (Exception ex) { exceptions.Add(ex); } }); thread.Start(); return(thread); }) .ToArray(); foreach (var thread in threads) { if (!thread.Join(timeoutMilliseconds)) { throw new TimeoutException(); } } if (exceptions.Any()) { throw exceptions.First(); } actionsExecutedCount.Should().Be(threadsCount); }
/// <summary> /// Creates the report summary. /// </summary> private void CreateReportSummary() { Dictionary <string, int> keys = new Dictionary <string, int>(); var root = eventItems.First().DataRow.Table; var clone = root.Clone(); foreach (var item in eventItems) //.Select(s=> s.PrimaryKey).Distinct().ToList()) { if (keys.ContainsKey(item.PrimaryKey)) { continue; } keys.Add(item.PrimaryKey, 0); var desRow = clone.NewRow(); desRow.ItemArray = item.DataRow.ItemArray.Clone() as object[]; clone.Rows.Add(desRow); } gridControl4.DataSource = clone; }
public ArticleInfoVO GetRandModel() { if (m_maxleng == 0) { Refresh(); } ArticleInfoVO info = _list.First(); int len = _random.Next(m_maxleng); for (int i = 0; i < m_maxleng; i++) { if (len == i) { info = _list.Skip(len).First(); } } return(info); }
public ActionResult OnPostFuka() { var data = GetData(); var ret = new ConcurrentBag <ActionResult>(); //各サーバのスペックで上限値は変わってくると思います(開発環境メモリ16gbでテスト) Parallel.For(0, 15, (i) => { var pdf = CreaetePdf("nomal.html", new List <JObject> { data[i] }); ret.Add(pdf.Result); } ); //とりあえずどれか戻す return(ret.First()); }
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 async Task WithDisconnectMessageWithTokenError_ShouldRenewTokenAndReconnect() { var client = await SetupConnectedClient(); List <ConnectionState> states = new List <ConnectionState>(); var errors = new ConcurrentBag <ErrorInfo>(); client.Connection.On((args) => { if (args.HasError) { errors.Add(args.Reason); } states.Add(args.Current); }); client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Disconnected) { Error = _tokenErrorInfo }); await client.ProcessCommands(); client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Connected)); await client.WaitForState(ConnectionState.Connected); _renewTokenCalled.Should().BeTrue(); Assert.Equal(new[] { ConnectionState.Disconnected, ConnectionState.Connecting, ConnectionState.Connected }, states); errors.Should().HaveCount(1); errors.First().Should().Be(_tokenErrorInfo); var currentToken = client.RestClient.AblyAuth.CurrentToken; currentToken.Token.Should().Be(_returnedDummyTokenDetails.Token); currentToken.ClientId.Should().Be(_returnedDummyTokenDetails.ClientId); currentToken.Expires.Should().BeCloseTo(_returnedDummyTokenDetails.Expires, TimeSpan.Zero); }
public async Task Reuses_CloudQueue_ForSameQueueName_OnConcurentCalls() { // prepare const string queueName = "test-queue-1"; ConcurrentBag <CloudQueue> queueBag = new ConcurrentBag <CloudQueue>(); int count = 10; List <Task> tasks = new List <Task>(); for (int i = 0; i < count; i++) { tasks.Add(Task.Run(async() => queueBag.Add(await _cloudQueueFactory.GetCloudQueue(queueName)))); } // execute await Task.WhenAll(tasks); // check // 10 queues created Assert.Equal(10, queueBag.Count); // all queues have the same name foreach (var q in queueBag) { Assert.Equal(queueName, q.Name); } // all queues are the same object var firstQueue = queueBag.First(); foreach (var q in queueBag) { Assert.True(object.ReferenceEquals(firstQueue, q)); } // .CreateIfNotExistsAsync() is invoked exactly once _cloudQueueClientMock.Received(1).GetQueueReference(Arg.Any <string>()); firstQueue.Received(1).CreateIfNotExistsAsync(); }
public async Task Reuses_CloudQueueClient_ForMultipleCloudQueues_OnConcurrentCalls() { // prepare const string queueNamePrefix = "test-queue-"; ConcurrentBag <CloudQueue> queueBag = new ConcurrentBag <CloudQueue>(); int count = 10; List <Task> tasks = new List <Task>(); for (int i = 0; i < count; i++) { var y = i; tasks.Add(Task.Run(async() => queueBag.Add(await _cloudQueueFactory.GetCloudQueue($"{queueNamePrefix}{y}")))); } // execute await Task.WhenAll(tasks); // check // 10 queues created Assert.Equal(10, queueBag.Count()); // not two queues have the same name Assert.Equal(10, queueBag.GroupBy(x => x.Name).Count()); // all queues are different object var firstQueue = queueBag.First(); foreach (var q in queueBag.Skip(1)) { Assert.False(object.ReferenceEquals(firstQueue, q)); } // ONLY ONE underlying CloudQueueClient has been created! _cloudQueueClientFactoryMock.Received(1).GetCloudQueueClient(); // CouldQueueClient has been reused to create each queue _cloudQueueClientMock.Received(10).GetQueueReference(Arg.Any <string>()); }
public User GetUser(int id) { User result; lock (_locker) { try { result = _users.First(user => user.Id == id); Console.WriteLine("T{0}[GET]: id{1} - {2}", Task.CurrentId, id, result.Name); return(result); } catch (Exception e) { Console.WriteLine("T{0}[GET]: id{1} not found", Task.CurrentId, id); return(null); } } }
/// <summary> /// recover key from 2 different reader responses on same tag challenge /// </summary> /// <param name="uid"></param> /// <param name="nt"></param> /// <param name="nr0"></param> /// <param name="ar0"></param> /// <param name="nr1"></param> /// <param name="ar1"></param> /// <returns>return ulong.MaxValue if key not found</returns> public static ulong MfKey32(uint uid, uint nt, uint nr0, uint ar0, uint nr1, uint ar1) { var p64 = Crypto1.PrngSuccessor(nt, 64); var list = Crapto1.LfsrRecovery32(ar0 ^ p64, 0); var keys = new ConcurrentBag <ulong>(); Parallel.ForEach(list, s => { var crapto1 = new Crapto1(s); crapto1.LfsrRollbackWord(); crapto1.LfsrRollbackWord(nr0, true); crapto1.LfsrRollbackWord(uid ^ nt); var key = crapto1.Lfsr; crapto1.Crypto1Word(uid ^ nt); crapto1.Crypto1Word(nr1, true); if (ar1 == (crapto1.Crypto1Word() ^ p64)) { keys.Add(key); } }); return(keys.Count == 1 ? keys.First() : ulong.MaxValue); }
public Option <Unit> Traverse(params Assembly[] assemblies) { var errors = new ConcurrentBag <Exception>(); assemblies.AsParallel().ForAll(a => { try { a.GetTypes().AsParallel() .ForAll(t => TraverseType(t) .OnNone(message => new Exception(message.Format(false)))); } catch (Exception e) { errors.Add(e); } }); return(errors.Any() ? none <Unit>(errors.First()) : some(Unit.Value)); }
public void FastAtomicLazy_only_single_value_creation_attempt() { int attempts = 0; Func <int> slowValueFactory = () => { Interlocked.Increment(ref attempts); Thread.Sleep(100); return(new Random().Next(1, Int32.MaxValue)); }; var values = new ConcurrentBag <int>(); var fal = new FastLazy <int>(slowValueFactory); 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))); Assert.Equal(1000, values.Count); Assert.Equal(1, attempts); }
public void FastAtomicLazy_only_single_value_creation_attempt_AnyRef() { int attempts = 0; Func <string> slowValueFactory = () => { Interlocked.Increment(ref attempts); Thread.Sleep(100); return(Faker.Generators.Strings.GenerateAlphaNumericString()); }; var values = new ConcurrentBag <string>(); var fal = new FastLazy <string>(slowValueFactory); 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))); Assert.Equal(1000, values.Count); Assert.Equal(1, attempts); }
static void Main(string[] args) { Console.ReadLine(); Console.WriteLine("Started"); var sw = Stopwatch.StartNew(); var inputIntegers = GenerateMD5InputData(); var hashesBag = new ConcurrentBag <string>(); try { inputIntegers.ForAll((i) => hashesBag.Add(GenerateMD5Hash(i))); Console.WriteLine("First MD5 hash: {0}", hashesBag.First()); Console.WriteLine("Started to show results in {0}", sw.Elapsed); Console.WriteLine("Last MD5 hash: {0}", hashesBag.Last()); Console.WriteLine("{0} MD5 hashes generated in {1}", hashesBag.Count(), sw.Elapsed.ToString()); } catch (AggregateException ex) { foreach (Exception innerEx in ex.InnerExceptions) { Debug.WriteLine(innerEx.ToString()); // Do something considering the innerEx Exception if (innerEx is InvalidOperationException) { Console.WriteLine(String.Format("The MD5 generator failed. Exception details: {0}", innerEx.Message)); } } // Something went wrong // Create a new empty ConcurrentBag with no results hashesBag = new ConcurrentBag <string>(); } Console.ReadLine(); }
public TestScenario GetTestScenario() { lock (_lockObj) { var rand = new Random(); int choice = rand.Next(_totalWeight); int sum = 0; foreach (var testScenario in _testScenarios.OrderBy(x => x.TimesExecuted - x.TimesToBeExecuted)) { for (int i = sum; i < testScenario.Weight + sum; i++) { if (i >= choice) { return(testScenario); } } sum += testScenario.Weight; } } return(_testScenarios.First()); }
public void ReturnsTokenForSingleRequest() { var sut = CreateInstance(_serverName, 2, TimeSpan.MinValue, TimeSpan.MinValue, -1, true); sut.TokenIssued += Sut_TokenIssued; var threadCount = 1; using (var countdownEvent = new CountdownEvent(threadCount)) { for (var i = 0; i < threadCount; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(PullToken_OnAThreadPool_Thread), new ThreadFuncObj { TokenRepo = sut, Tokens = _tokensIssued, SyncObj = countdownEvent }); } countdownEvent.Wait(); } var token = _tokensIssued.First(); Assert.NotNull(token); Assert.Equal(_clientName, token.Client); Assert.Empty(_callbackMaxTokensIssued); Assert.Single(_callbackTokensIssued); Assert.Equal(_clientName, _callbackTokensIssued.First().Client); Assert.Equal(_serverName, token.Server); Assert.NotNull(token.Id); Assert.Equal(constTokenId, token.Id); /* Time validation does not work, due to how threading works, unless we give large time gaps, * at which point time check is irrelevant. * Assert.True(DateTime.Now - token.IssuedOn > TimeSpan.FromMilliseconds(1)); * Assert.True(DateTime.Now - token.IssuedOn < TimeSpan.FromMilliseconds(10)); */ }
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 LogicalCallTelemetryInitializerAddsProperties() { var events = new ConcurrentBag <ITelemetry>(); var instrumentationKey = Guid.NewGuid().ToString(); var containerBuilder = new ContainerBuilder(); containerBuilder.Register(c => new TelemetryClientBuilder().AddInitializers(c.Resolve <IEnumerable <ITelemetryInitializer> >()).Build(t => events.Add(t))); containerBuilder.Register(c => new TelemetrySettings { InstrumentationKey = instrumentationKey, InternalKey = Guid.Empty.ToString() }); containerBuilder.RegisterModule <TelemetryModule>(); var container = containerBuilder.Build(); var bb = container.Resolve <IBigBrother>(); LogicalCallTelemetryInitializer.Instance.SetProperty("TestProp", "TestValue"); bb.Publish(new TestEvent()); bb.Flush(); events.Should().HaveCount(1); events.First().Should().BeOfType <EventTelemetry>() .Which.Properties.Should().ContainKey("TestProp") .WhichValue.Should().Be("TestValue"); }
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 async Task<List<TimeSpan>> Run() { var results = new List<TimeSpan>(); for (var n = 0; n < NoOfIterations; n++) { DateTime start = DateTime.Now; var proposers = new ConcurrentBag<Proposer>(); var acceptors = new ConcurrentBag<Acceptor>(); var proposedValues = new ConcurrentBag<string>(); var acceptedValues = new ConcurrentBag<Task<string>>(); for (int i = 0; i < Proposers; i++) { proposers.Add(new Proposer(Guid.NewGuid().ToString(), Acceptors)); } for (int i = 0; i < LiveAcceptors; i++) { acceptors.Add(new Acceptor("Address")); } foreach (var proposer in proposers) foreach (var acceptor in acceptors) proposer.Pipe(new Delay<NetworkMessage>(TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay))) .Pipe(new Drop<NetworkMessage>(drop)) .Pipe(acceptor) .Pipe(new Delay<NetworkMessage>(TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay))) .Pipe(new Drop<NetworkMessage>(drop)) .Pipe(proposer); foreach (var proposer in proposers) { acceptedValues.Add(Task.Factory.StartNew(() => { var val = Guid.NewGuid().ToString(); proposedValues.Add(val); return proposer.Propose(val); }) .Unwrap()); } var acceptedValue = await acceptedValues.First(); foreach (var res in acceptedValues) { var result = await res; if (result != acceptedValue) throw new Exception("The proposers did not all get the same result"); if (!proposedValues.Contains(result)) throw new Exception("The accepted Value was never proposed"); } DateTime end = DateTime.Now; results.Add(end.Subtract(start)); } return results; }
public void TestSession() { _dumps = new ConcurrentBag<ICollection<Operation>>(); var ignite = Ignition.GetIgnite(IgniteName); var cache1 = Ignition.GetIgnite(IgniteName).Cache<int, int>(Cache1); var cache2 = Ignition.GetIgnite(IgniteName).Cache<int, int>(Cache2); // 1. Test rollback. using (var tx = ignite.Transactions.TxStart()) { cache1.Put(1, 1); cache2.Put(2, 2); tx.Rollback(); } Assert.AreEqual(1, _dumps.Count); var ops = _dumps.First(); Assert.AreEqual(1, ops.Count); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.SesEnd && !op.Commit)); _dumps = new ConcurrentBag<ICollection<Operation>>(); // 2. Test puts. using (var tx = ignite.Transactions.TxStart()) { cache1.Put(1, 1); cache2.Put(2, 2); tx.Commit(); } Assert.AreEqual(1, _dumps.Count); ops = _dumps.First(); Assert.AreEqual(3, ops.Count); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Write && Cache1.Equals(op.CacheName) && 1.Equals(op.Key) && 1.Equals(op.Value))); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Write && Cache2.Equals(op.CacheName) && 2.Equals(op.Key) && 2.Equals(op.Value))); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.SesEnd && op.Commit)); _dumps = new ConcurrentBag<ICollection<Operation>>(); // 3. Test removes. using (var tx = ignite.Transactions.TxStart()) { cache1.Remove(1); cache2.Remove(2); tx.Commit(); } Assert.AreEqual(1, _dumps.Count); ops = _dumps.First(); Assert.AreEqual(3, ops.Count); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Delete && Cache1.Equals(op.CacheName) && 1.Equals(op.Key))); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.Delete && Cache2.Equals(op.CacheName) && 2.Equals(op.Key))); Assert.AreEqual(1, ops.Count(op => op.Type == OperationType.SesEnd && op.Commit)); }
public void Multiple_contexts_running_concurrently_can_use_interception() { var loggers = new ConcurrentBag<CommandLogger>(); const int executionCount = 5; ExecuteInParallel( () => { using (var context = new BlogContextNoInit()) { var logger = new CommandLogger(context); DbInterception.Add(logger); loggers.Add(logger); try { BlogContext.DoStuff(context); } finally { DbInterception.Remove(logger); } var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length]; for (var i = 0; i < logger.Log.Count; i++) { var method = logger.Log[i].Method; commandsUsed[(int)method] = true; if (method.ToString().EndsWith("Executing")) { Assert.Equal(method + 1, logger.Log[i + 1].Method); Assert.Same(logger.Log[i].Command, logger.Log[i + 1].Command); } } // Check that expected command have log entries Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]); Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]); Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]); Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]); #if !NET40 Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]); Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]); #endif // Sanity check on command text var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant()); Assert.True(commandTexts.Any(c => c.StartsWith("select"))); Assert.True(commandTexts.Any(c => c.StartsWith("insert"))); #if !NET40 Assert.True(commandTexts.Any(c => c.StartsWith("update"))); #endif // Sanity check on results Assert.True(logger.Log.Where(l => l.Method == CommandMethod.NonQueryExecuted).All(l => l.Result != null)); Assert.True(logger.Log.Where(l => l.Method == CommandMethod.ReaderExecuted).All(l => l.Result != null)); } }, executionCount); // Check that each execution logged exactly the same commands. Assert.Equal(executionCount, loggers.Count); var firstLog = loggers.First().Log; foreach (var log in loggers.Select(l => l.Log).Skip(1)) { Assert.Equal(firstLog.Count, log.Count); for (var i = 0; i < log.Count; i++) { Assert.Equal(firstLog[i].Method, log[i].Method); Assert.Equal(firstLog[i].CommandText, log[i].CommandText); if (firstLog[i].Result == null) { Assert.Null(log[i].Result); } else { Assert.Same(firstLog[i].Result.GetType(), log[i].Result.GetType()); } } } }
public void DCAwareRoundRobinPolicyWithNodesChanging() { var hostList = new ConcurrentBag<Host> { TestHelper.CreateHost("0.0.0.1", "dc1"), TestHelper.CreateHost("0.0.0.2", "dc2"), TestHelper.CreateHost("0.0.0.3", "dc1"), TestHelper.CreateHost("0.0.0.4", "dc2"), TestHelper.CreateHost("0.0.0.5", "dc1"), TestHelper.CreateHost("0.0.0.6", "dc2"), TestHelper.CreateHost("0.0.0.7", "dc1"), TestHelper.CreateHost("0.0.0.8", "dc2"), TestHelper.CreateHost("0.0.0.9", "dc1"), TestHelper.CreateHost("0.0.0.10", "dc2") }; const string localDc = "dc1"; //to remove the host 3 var hostToRemove = hostList.First(h => TestHelper.GetLastAddressByte(h) == 3); var clusterMock = new Mock<ICluster>(); clusterMock .Setup(c => c.AllHosts()) .Returns(() => { return hostList.ToList(); }); //Initialize the balancing policy var policy = new DCAwareRoundRobinPolicy(localDc, 1); policy.Initialize(clusterMock.Object); var hostYielded = new ConcurrentBag<IEnumerable<Host>>(); Action action = () => hostYielded.Add(policy.NewQueryPlan(null, null).ToList()); //Invoke without nodes changing TestHelper.ParallelInvoke(action, 100); Assert.True(hostYielded.Any(hl => hl.Any(h => h == hostToRemove))); var actionList = new List<Action>(Enumerable.Repeat<Action>(action, 1000)); actionList.Insert(200, () => { var host = TestHelper.CreateHost("0.0.0.11", "dc1"); //raise event and then add clusterMock.Raise(c => c.HostAdded += null, host); hostList.Add(host); }); actionList.Insert(400, () => { var host = TestHelper.CreateHost("0.0.0.12", "dc1"); //first add and then raise event hostList.Add(host); clusterMock.Raise(c => c.HostAdded += null, host); }); actionList.Insert(400, () => { var host = hostToRemove; hostList = new ConcurrentBag<Host>(hostList.Where(h => h != hostToRemove)); clusterMock.Raise(c => c.HostRemoved += null, host); }); //Invoke it with nodes being modified TestHelper.ParallelInvoke(actionList); //Clear the host yielded so far hostYielded = new ConcurrentBag<IEnumerable<Host>>(); //Invoke it a some of times more in parallel TestHelper.ParallelInvoke(action, 100); //The removed node should not be returned Assert.False(hostList.Any(h => h == hostToRemove)); Assert.False(hostYielded.Any(hl => hl.Any(h => h == hostToRemove))); }
private static void SampleConnections(CrankArguments arguments, ConcurrentBag<Connection> connections, TimeSpan elapsed) { var connecting = connections.Count(c => c.State == ConnectionState.Connecting); var connected = connections.Count(c => c.State == ConnectionState.Connected); var reconnecting = connections.Count(c => c.State == ConnectionState.Reconnecting); var disconnected = connections.Count(c => c.State == ConnectionState.Disconnected); Mark(arguments, (ulong)connecting, "Connections Connecting"); Mark(arguments, (ulong)connected, "Connections Connected"); Mark(arguments, (ulong)reconnecting, "Connections Reconnecting"); Mark(arguments, (ulong)disconnected, "Connections Disconnected"); var transportState = ""; if (connections.First().Transport.GetType() == typeof(AutoTransport)) { transportState = String.Format(", Transport={0}ws|{1}ss|{2}lp", connections.Count(c => c.Transport.Name.Equals("webSockets", StringComparison.InvariantCultureIgnoreCase)), connections.Count(c => c.Transport.Name.Equals("serverSentEvents", StringComparison.InvariantCultureIgnoreCase)), connections.Count(c => c.Transport.Name.Equals("longPolling", StringComparison.InvariantCultureIgnoreCase))); } Console.WriteLine(String.Format("[{0}] Connections: {1}/{2}, State={3}|{4}c|{5}r|{6}d", elapsed, connections.Count(), arguments.NumClients, connecting, connected, reconnecting, disconnected) + transportState); }
private async Task StartSimulation() { if(Simulator.SongData==null) { MessageBox.Show("楽曲を選んでください"); return; } if (Simulator.Unit == null) { MessageBox.Show("ユニットを選んでください"); return; } if (Runs < 1 || Runs > 1000000) { MessageBox.Show("試行回数は1から1,000,000までである必要があります"); return; } Note[] pattern = null; if (UtilizeActualPattern) { pattern = await new PatternProvider().GetPattern(Simulator.Song, Simulator.SongData.Difficulty, Simulator.SongData.Notes); if (pattern == null) { MessageBox.Show($"{Simulator.Song.Title}({Simulator.SongData.Difficulty})の譜面データが見つかりませんでした。"); return; } } SimulationCompleted = false; var results = new ConcurrentBag<SimulationResult>(); await Task.Run(() => Parallel.For(1, Runs+1, i => results.Add(Simulator.StartSimulation(RandomFactory.Create(), i, pattern == null ? null : new Queue<Note>(pattern))))); MaxScore = results.Max(x=>x.Score); MaxScorePerNote = results.Max(x => x.ScorePerNote); MinScore = results.Min(x => x.Score); MinScorePerNote = results.Min(x => x.ScorePerNote); AverageScore = (int)results.Average(x => x.Score); AverageScorePerNote = (int)results.Average(x => x.ScorePerNote); ScoreDistribution = results.GroupBy(x => (int)Math.Floor(x.Score / 10000.0)).OrderBy(x => x.Key).ToDictionary(x => x.Key, x => (double)x.Count() / results.Count); StandardDeviation = Math.Round(Math.Sqrt(results.Sum(x => Math.Pow(x.Score - AverageScore, 2))) / results.Count); int idx = 1; var duration = results.First().Duration; ActualTriggerRatio = Simulator.Unit.Slots.ToDictionary(s => $"スロット{idx++}", s => s == null ? 0 : results.SelectMany(x => x.TriggeredSkills).Where(x => x.Who == s).Count() / (results.Count * Math.Floor((duration - 1.0) / s.Skill.Interval))); SimulationResults = results.OrderBy(x => x.Id).Take(100).ToList(); SelectedResult = SimulationResults[0]; SimulationCompleted = true; }
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 WHEN_creating_1K_of_objects_THEN_can_change_property_to_an_object() { var actors = new ConcurrentBag<TestActor>(); for (int i = 0; i < 1000; i++) { var id = Guid.NewGuid(); actors.Add(new TestActor { Id = id, Payload = string.Format("Actor Id: {0}", id.ToString()) }); } Assert.AreEqual(1000, actors.Count); // Change property by a variable that reference the element in the collection var actor = actors.First(); Assert.AreNotEqual(Guid.Empty, actor.Id); actor.Id = Guid.Empty; Assert.AreEqual(Guid.Empty, actors.First().Id); // Change property directly to the element in the collection Assert.AreNotEqual(Guid.Empty, actors.Last().Id); actors.Last().Id = Guid.Empty; Assert.AreEqual(Guid.Empty, actors.Last().Id); // Changing property in a loop Assert.IsTrue(actors.Where(a => a.Id != Guid.Empty).Any()); foreach (var a in actors) { a.Id = Guid.Empty; } Assert.IsFalse(actors.Where(a => a.Id != Guid.Empty).Any()); }