Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Diagnostics;
- namespace ConsoleTestApp;
- public class LazyThreadSafeCookieCounter
- {
- private readonly object _cookiesLock = new();
- private int _cookies = 0;
- public int Cookies { get => _cookies; private set => _cookies = value; }
- private static readonly object _instanceLock = new();
- private static LazyThreadSafeCookieCounter? Instance { get; set; }
- private LazyThreadSafeCookieCounter() { }
- public static LazyThreadSafeCookieCounter GetInstance()
- {
- lock (_instanceLock)
- {
- Instance ??= new LazyThreadSafeCookieCounter();
- }
- return Instance;
- }
- public void IncrementCookie()
- {
- Interlocked.Increment(ref _cookies);
- }
- public void ClearCookies()
- {
- Cookies = 0;
- }
- }
- public static class Program
- {
- public async static Task Main()
- {
- var cookieCounter = LazyThreadSafeCookieCounter.GetInstance();
- IncrementTenMillionTimes(cookieCounter).RunSynchronously();
- cookieCounter.ClearCookies();
- GC.Collect();
- Console.WriteLine("Cookies amount before: " + cookieCounter.Cookies);
- var stopwatch = new Stopwatch();
- var task = IncrementTenMillionTimes(cookieCounter);
- stopwatch.Start();
- task.RunSynchronously();
- stopwatch.Stop();
- Console.WriteLine("Cookies amount after: " + cookieCounter.Cookies);
- Console.WriteLine("Time spent: " + stopwatch.Elapsed.TotalMilliseconds + " ms");
- Console.WriteLine("Done.");
- }
- public static Task IncrementTenMillionTimes(LazyThreadSafeCookieCounter cookieCounter)
- {
- void incrementHundredThousandTimes()
- {
- for (var i = 0; i < 100_000; i++)
- cookieCounter.IncrementCookie();
- }
- return new Task(() =>
- {
- Parallel.For(fromInclusive: 0,
- toExclusive: 100,
- (int iteration, ParallelLoopState loopState) => incrementHundredThousandTimes());
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement