Advertisement
Catsher

LazyThreadSafeCookieCounter

Mar 26th, 2025
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. using System.Diagnostics;
  2.  
  3. namespace ConsoleTestApp;
  4.  
  5. public class LazyThreadSafeCookieCounter
  6. {
  7.     private readonly object _cookiesLock = new();
  8.     private int _cookies = 0;
  9.     public int Cookies { get => _cookies; private set => _cookies = value; }
  10.  
  11.     private static readonly object _instanceLock = new();
  12.     private static LazyThreadSafeCookieCounter? Instance { get; set; }
  13.  
  14.     private LazyThreadSafeCookieCounter() { }
  15.  
  16.     public static LazyThreadSafeCookieCounter GetInstance()
  17.     {
  18.         lock (_instanceLock)
  19.         {
  20.             Instance ??= new LazyThreadSafeCookieCounter();
  21.         }
  22.  
  23.         return Instance;
  24.     }
  25.  
  26.     public void IncrementCookie()
  27.     {
  28.         Interlocked.Increment(ref _cookies);
  29.     }
  30.  
  31.     public void ClearCookies()
  32.     {
  33.         Cookies = 0;
  34.     }
  35. }
  36.  
  37. public static class Program
  38. {
  39.     public async static Task Main()
  40.     {
  41.         var cookieCounter = LazyThreadSafeCookieCounter.GetInstance();
  42.  
  43.         IncrementTenMillionTimes(cookieCounter).RunSynchronously();
  44.         cookieCounter.ClearCookies();
  45.         GC.Collect();
  46.  
  47.         Console.WriteLine("Cookies amount before: " + cookieCounter.Cookies);
  48.  
  49.         var stopwatch = new Stopwatch();
  50.        
  51.         var task = IncrementTenMillionTimes(cookieCounter);
  52.  
  53.         stopwatch.Start();
  54.         task.RunSynchronously();
  55.         stopwatch.Stop();
  56.        
  57.         Console.WriteLine("Cookies amount after: " + cookieCounter.Cookies);
  58.         Console.WriteLine("Time spent: " + stopwatch.Elapsed.TotalMilliseconds + " ms");
  59.         Console.WriteLine("Done.");
  60.     }
  61.  
  62.     public static Task IncrementTenMillionTimes(LazyThreadSafeCookieCounter cookieCounter)
  63.     {
  64.         void incrementHundredThousandTimes()
  65.         {
  66.             for (var i = 0; i < 100_000; i++)
  67.                 cookieCounter.IncrementCookie();
  68.         }
  69.  
  70.         return new Task(() =>
  71.         {
  72.             Parallel.For(fromInclusive: 0,
  73.                         toExclusive: 100,
  74.                         (int iteration, ParallelLoopState loopState) => incrementHundredThousandTimes());
  75.         });
  76.     }
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement