本文整理汇总了C#中ConcurrentDictionary.Sum方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.Sum方法的具体用法?C# ConcurrentDictionary.Sum怎么用?C# ConcurrentDictionary.Sum使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentDictionary
的用法示例。
在下文中一共展示了ConcurrentDictionary.Sum方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CanHandleMultipleWorkItemInstances
public async Task CanHandleMultipleWorkItemInstances() {
const int workItemCount = 1000;
using (var metrics = new InMemoryMetricsClient(loggerFactory: Log)) {
using (var queue = new InMemoryQueue<WorkItemData>(retries: 0, retryDelay: TimeSpan.Zero, loggerFactory: Log)) {
queue.AttachBehavior(new MetricsQueueBehavior<WorkItemData>(metrics, loggerFactory: Log));
using (var messageBus = new InMemoryMessageBus(Log)) {
var handlerRegistry = new WorkItemHandlers();
var j1 = new WorkItemJob(queue, messageBus, handlerRegistry, Log);
var j2 = new WorkItemJob(queue, messageBus, handlerRegistry, Log);
var j3 = new WorkItemJob(queue, messageBus, handlerRegistry, Log);
int errors = 0;
var jobIds = new ConcurrentDictionary<string, int>();
handlerRegistry.Register<MyWorkItem>(async ctx => {
var jobData = ctx.GetData<MyWorkItem>();
Assert.Equal("Test", jobData.SomeData);
var jobWorkTotal = jobIds.AddOrUpdate(ctx.JobId, 1, (key, value) => value + 1);
if (jobData.Index % 100 == 0)
_logger.Trace("Job {jobId} processing work item #: {jobWorkTotal}", ctx.JobId, jobWorkTotal);
for (int i = 0; i < 10; i++)
await ctx.ReportProgressAsync(10 * i);
if (RandomData.GetBool(1)) {
Interlocked.Increment(ref errors);
throw new Exception("Boom!");
}
});
for (int i = 0; i < workItemCount; i++)
await queue.EnqueueAsync(new MyWorkItem {
SomeData = "Test",
Index = i
}, true);
var completedItems = new List<string>();
object completedItemsLock = new object();
messageBus.Subscribe<WorkItemStatus>(status => {
if (status.Progress == 100)
_logger.Trace("Progress: {progress}", status.Progress);
if (status.Progress < 100)
return;
lock (completedItemsLock)
completedItems.Add(status.WorkItemId);
});
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var tasks = new List<Task> {
Task.Run(async () => {
await j1.RunUntilEmptyAsync(cancellationTokenSource.Token);
cancellationTokenSource.Cancel();
}, cancellationTokenSource.Token),
Task.Run(async () => {
await j2.RunUntilEmptyAsync(cancellationTokenSource.Token);
cancellationTokenSource.Cancel();
}, cancellationTokenSource.Token),
Task.Run(async () => {
await j3.RunUntilEmptyAsync(cancellationTokenSource.Token);
cancellationTokenSource.Cancel();
}, cancellationTokenSource.Token)
};
try {
await Task.WhenAll(tasks);
await SystemClock.SleepAsync(100);
} catch (TaskCanceledException) {}
_logger.Info("Completed: {completedItems} Errors: {errors}", completedItems.Count, errors);
Assert.Equal(workItemCount, completedItems.Count + errors);
Assert.Equal(3, jobIds.Count);
Assert.Equal(workItemCount, jobIds.Sum(kvp => kvp.Value));
}
}
}
}
示例2: CanDoCompetingConsumers
public void CanDoCompetingConsumers(int messageCount, int threadCount)
{
using (CreateQueue(InputQueueName).Purge()) { }
var keepRunning = true;
var lastMessageReceivedTime = DateTime.UtcNow;
var receivedMessagesDistribution = new ConcurrentDictionary<int, int>();
var receivers = Enumerable.Range(0, threadCount)
.Select(i =>
{
var queue = TrackDisposable(CreateQueue(InputQueueName));
var number = i + 1;
return new Thread(() =>
{
Console.WriteLine("Receiver {0} started", number);
while (keepRunning)
{
using (var tx = new TransactionScope())
{
var receivedMessage = queue.ReceiveMessage(new AmbientTransactionContext());
if (receivedMessage != null)
{
receivedMessagesDistribution.AddOrUpdate(number, (key) => 1, (key, value) => value + 1);
Console.Write(".");
lastMessageReceivedTime = DateTime.UtcNow;
}
tx.Complete();
}
}
Console.WriteLine("Receiver {0} stopped", number);
});
})
.ToList();
var sender = CreateQueue("test_competing_sender");
Console.WriteLine("Sending {0} messages", messageCount);
messageCount.Times(() => sender.Send(InputQueueName, new TransportMessageToSend
{
Headers = new Dictionary<string, object>(),
Body = Encoding.UTF8.GetBytes("w00000t!")
}, new NoTransaction()));
Console.WriteLine("Starting {0} receivers", receivers.Count);
receivers.ForEach(r => r.Start());
lastMessageReceivedTime = DateTime.UtcNow;
while (lastMessageReceivedTime.ElapsedUntilNow() < 3.Seconds())
{
Console.WriteLine("Waiting...");
Thread.Sleep(2.Seconds());
}
Console.WriteLine("Stopping receivers...");
keepRunning = false;
receivers.ForEach(r => r.Join());
Console.WriteLine("Got {0} messages distributed among workers like this:", receivedMessagesDistribution.Sum(d => d.Value));
Console.WriteLine(string.Join(Environment.NewLine, receivedMessagesDistribution.Select(kvp => string.Format("{0:000}: {1}", kvp.Key, new string('=', kvp.Value)))));
}
示例3: CanHandleMultipleWorkItemInstances
public async Task CanHandleMultipleWorkItemInstances()
{
var metrics = new InMemoryMetricsClient();
var queue = new InMemoryQueue<WorkItemData>(retryDelay: TimeSpan.Zero, retries: 0);
queue.AttachBehavior(new MetricsQueueBehavior<WorkItemData>(metrics));
var messageBus = new InMemoryMessageBus();
var handlerRegistry = new WorkItemHandlers();
var j1 = new WorkItemJob(queue, messageBus, handlerRegistry);
var j2 = new WorkItemJob(queue, messageBus, handlerRegistry);
var j3 = new WorkItemJob(queue, messageBus, handlerRegistry);
int errors = 0;
var jobIds = new ConcurrentDictionary<string, int>();
handlerRegistry.Register<MyWorkItem>(ctx => {
var jobData = ctx.GetData<MyWorkItem>();
Assert.Equal("Test", jobData.SomeData);
jobIds.AddOrUpdate(ctx.JobId, 1, (key, value) => value + 1);
for (int i = 0; i < 10; i++)
ctx.ReportProgress(10 * i);
if (RandomData.GetBool(1))
{
Interlocked.Increment(ref errors);
throw new ApplicationException("Boom!");
}
return TaskHelper.Completed();
});
for (int i = 0; i < 100; i++)
queue.Enqueue(new MyWorkItem { SomeData = "Test", Index = i }, true);
var completedItems = new List<string>();
object completedItemsLock = new object();
messageBus.Subscribe<WorkItemStatus>(status =>
{
if (status.Progress < 100)
return;
lock (completedItemsLock)
completedItems.Add(status.WorkItemId);
});
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var token = cancellationTokenSource.Token;
var tasks = new List<Task>();
tasks.AddRange(new[] {
Task.Run(async () => await j1.RunUntilEmptyAsync(token), token),
Task.Run(async () => await j2.RunUntilEmptyAsync(token), token),
Task.Run(async () => await j3.RunUntilEmptyAsync(token), token),
});
await Task.WhenAll(tasks);
Thread.Sleep(10);
Assert.Equal(100, completedItems.Count + errors);
Assert.Equal(3, jobIds.Count);
Assert.Equal(100, jobIds.Sum(kvp => kvp.Value));
}
示例4: ShowModificationImportWindowDialog
public void ShowModificationImportWindowDialog(string modificationPath)
{
var rootNodeViewModel = modificationImportViewModelFactory.FromDirectory(modificationPath);
var solution = riotSolutionLoader.Load(@"V:\Riot Games\League of Legends\RADS", RiotProjectType.AirClient | RiotProjectType.GameClient);
var airResolver = new Resolver(solution.ProjectsByType[RiotProjectType.AirClient].ReleaseManifest.Root);
var gameResolver = new Resolver(solution.ProjectsByType[RiotProjectType.GameClient].ReleaseManifest.Root);
var fileNodes = rootNodeViewModel.EnumerateFileNodes().ToArray();
var importWindow = new ModificationImportWindow();
var modificationImportViewModel = new ModificationImportViewModel(this, importWindow, rootNodeViewModel);
modificationImportViewModel.ModificationFriendlyName = fileSystemProxy.GetDirectoryInfo(modificationPath).Name;
importWindow.DataContext = modificationImportViewModel;
new Thread(() => {
foreach (var fileNode in fileNodes) {
var path = fileNode.Path;
var airResolution = airResolver.Resolve(path);
if (airResolution.Any()) {
fileNode.ResolutionPath = airResolution.First().GetPath();
fileNode.ResolutionState = ResolutionState.ResolutionSuccessful;
} else {
var gameResolutions = gameResolver.Resolve(path);
if (gameResolutions.Any()) {
fileNode.ResolutionPath = gameResolutions.First().GetPath();
fileNode.ResolutionState = ResolutionState.ResolutionSuccessful;
} else {
fileNode.ResolutionState = ResolutionState.ResolutionFailed;
}
}
}
LeagueModificationCategory modificationType = LeagueModificationCategory.Other;
if (fileNodes.Any(node => node.ResolutionState == ResolutionState.ResolutionSuccessful)) {
var modificationTypeCounts = new ConcurrentDictionary<LeagueModificationCategory, int>();
foreach (var file in fileNodes) {
if (file.ResolutionState == ResolutionState.ResolutionSuccessful) {
if (file.ResolutionPath.IndexOf("DATA/Characters", StringComparison.OrdinalIgnoreCase) != -1 ||
file.ResolutionPath.IndexOf("assets/images/champions", StringComparison.OrdinalIgnoreCase) != -1) {
if (file.ResolutionPath.IndexOf("ward", StringComparison.OrdinalIgnoreCase) != -1) {
modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Ward, 1, (existing, count) => count + 1);
} else {
modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Champion, 1, (existing, count) => count + 1);
}
} else if (file.ResolutionPath.IndexOf("LEVELS") != -1) {
modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Map, 1, (existing, count) => count + 1);
} else if (file.ResolutionPath.IndexOf("Menu", StringComparison.OrdinalIgnoreCase) != -1) {
modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.UserInterface, 1, (existing, count) => count + 1);
} else {
modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Other, 1, (existing, count) => count + 1);
}
}
}
var categorizationCounts = modificationTypeCounts.Sum(x => x.Value);
var highestCategorization = modificationTypeCounts.MaxBy(key => key.Value, Comparer<int>.Default);
if (highestCategorization.Value >= categorizationCounts * 2.0 / 3.0) {
modificationType = modificationTypeCounts.MaxBy(key => key.Value, Comparer<int>.Default).Key;
}
Console.WriteLine("Highest categorization: " + highestCategorization.Key.Name);
modificationTypeCounts.ForEach(x => Console.WriteLine(x.Key.Name + ": " + x.Value));
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, new Action(() => {
modificationImportViewModel.ModificationCategorization = modificationType;
}));
}
}).Start();
importWindow.ShowDialog();
}