Skip to content

Instantly share code, notes, and snippets.

@mennankara
Created August 28, 2012 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mennankara/3500955 to your computer and use it in GitHub Desktop.
Save mennankara/3500955 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, PrivateClass> SomeClasses =
new ConcurrentDictionary<int, PrivateClass>();
private readonly PrivateClass _privateClass;
public SomeClass(int cachedInstanceId)
{
_privateClass = SomeClasses.GetOrAdd(cachedInstanceId, (key) => new Lazy<PrivateClass>(() => new PrivateClass(key)).Value);
}
public int SomeCalculationResult()
{
return _privateClass.CalculateSomething();
}
private class PrivateClass
{
public PrivateClass(int id)
{
Thread.Sleep(1000);
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
// CONSTUCTOR
// CONSTUCTOR
// CALCULATOR
// CALCULATOR
// CONSTUCTOR
// CALCULATOR
// CALCULATOR
// Sleeping a bit
// CALCULATOR
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment