Skip to content

Instantly share code, notes, and snippets.

@sfilatov
Last active June 11, 2018 16:10
Show Gist options
  • Save sfilatov/b784877ec51952752db8e055e1719553 to your computer and use it in GitHub Desktop.
Save sfilatov/b784877ec51952752db8e055e1719553 to your computer and use it in GitHub Desktop.
ConcurrentDictionary execution test
namespace ConsoleApp1
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Test started:");
ConcurrentReadWriteTest().Wait();
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
public static async Task ConcurrentReadWriteTest()
{
var dict = new ConcurrentDictionary<string, Metadata>();
var count = 1000;
dict.TryAdd(string.Empty, new Metadata());
var updateTasks = Enumerable.Repeat(0, count).Select(
_ => Task.Run(
() => dict.AddOrUpdate(
string.Empty,
(k) => new Metadata(),
(k, v) =>
{
// return new Metadata() { Version = v.Version + 1 };
v.Version++;
return v;
})));
var deleteTasks = Enumerable.Repeat(0, count).Select(
_ => Task.Run(
() => dict.AddOrUpdate(
string.Empty,
(k) => new Metadata(),
(k, v) =>
{
// return new Metadata() { Version = v.Version - 1 };
v.Version--;
return v;
})));
await Task.WhenAll(updateTasks);
await Task.WhenAll(deleteTasks);
Metadata result;
while (!dict.TryGetValue(string.Empty, out result))
{
}
Console.WriteLine($"Results {result.Version}");
}
private class Metadata
{
public int Version { get; set; } = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment