Skip to content

Instantly share code, notes, and snippets.

@aliostad
Last active December 22, 2015 05:48
Show Gist options
  • Save aliostad/6426371 to your computer and use it in GitHub Desktop.
Save aliostad/6426371 to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
Func<string> getStuff = () =>
{
Console.WriteLine("Called!");
return Guid.NewGuid().ToString();
};
var concurrentDictionary = new ConcurrentDictionary<int, string>();
concurrentDictionary.GetOrAdd(1, _ => "casd");
concurrentDictionary.GetOrAdd(1, _ => getStuff());
Console.WriteLine("You do not see a 'Called!' above");
Console.Read();
}
}
class ProgramContention
{
static void Main(string[] args)
{
var color = Console.ForegroundColor;
int counter = 0;
Func<string> getStuff = () =>
{
Interlocked.Increment(ref counter);
return Guid.NewGuid().ToString();
};
var concurrentDictionary = new ConcurrentDictionary<int, string>();
concurrentDictionary.GetOrAdd(1, _ => "casd");
Parallel.For((int) 1, 90000, (i) => concurrentDictionary.GetOrAdd(i/3, _ => getStuff()));
//Console.WriteLine("You do not see a 'Called!' above");
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("Expected 30000 but was ");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(counter);
Console.ForegroundColor = color;
Console.Read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment