Skip to content

Instantly share code, notes, and snippets.

@mennankara
Created August 28, 2012 17:59
Show Gist options
  • Save mennankara/3501446 to your computer and use it in GitHub Desktop.
Save mennankara/3501446 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace GeneralTests
{
internal class Program
{
public class SomeClass
{
private static readonly ConcurrentDictionary<int, Lazy<PrivateClass>> SomeClasses =
new ConcurrentDictionary<int, Lazy<PrivateClass>>();
private readonly PrivateClass _privateClass;
public SomeClass(int cachedInstanceId)
{
_privateClass = SomeClasses.GetOrAdd(cachedInstanceId, (key) => new Lazy<PrivateClass>()).Value;
}
public int SomeCalculationResult()
{
return _privateClass.CalculateSomething();
}
private class PrivateClass
{
public PrivateClass()
{
Thread.Sleep(10000);
Console.WriteLine("CONSTUCTOR");
}
internal int CalculateSomething()
{
Console.WriteLine("CALCULATOR");
return 10;
}
}
}
private static void Main(string[] args)
{
var tasks = new Task[Environment.ProcessorCount];
for (int i = 0; i < Environment.ProcessorCount; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
new SomeClass(1).SomeCalculationResult();
});
}
Task.WaitAll(tasks);
Console.WriteLine("Sleeping a bit");
Thread.Sleep(2000);
new SomeClass(1).SomeCalculationResult();
// Output:
// CONSTUCTOR
// CALCULATOR
// CALCULATOR
// CALCULATOR
// CALCULATOR
// Sleeping a bit
// CALCULATOR
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment