Created
August 28, 2012 17:13
-
-
Save mennankara/3500955 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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