本文整理汇总了C#中ConcurrentBag.First方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.First方法的具体用法?C# ConcurrentBag.First怎么用?C# ConcurrentBag.First使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.First方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartSimulation
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;
}
示例2: SampleConnections
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);
}
示例3: DCAwareRoundRobinPolicyWithNodesChanging
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)));
}
示例4: TestSession
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));
}
示例5: Multiple_contexts_running_concurrently_can_use_interception
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());
}
}
}
}
示例6: Model_hash_can_be_calculated_from_multiple_threads_using_a_single_DbCompiledModel
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));
}
示例7: EDMX_can_be_written_from_multiple_threads_using_a_single_DbCompiledModel
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));
}
示例8: Run
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;
}
示例9: WHEN_creating_1K_of_objects_THEN_can_change_property_to_an_object
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());
}