loading
open in
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Threading;

class MainClass {
  private static SemaphoreSlim _throttle = new SemaphoreSlim(2);

  public static void Main (string[] args) {

    InitializeThreadStoreSlot("ApplicationLogger");

    UserController userController = new UserController();

    ProductController productController = new ProductController();

    productController.SetOutofStock("6035");

    userController.RegisterUser("David", "33333");

    _throttle.Wait();
    Thread t1 = new Thread(() =>
    {
        InitializeThreadStoreSlot("ProductLogger");

        productController.SetOutofStock("1002");

        _throttle.Release();
    });

    _throttle.Wait();
    Thread t2 = new Thread(() =>
    {
        InitializeThreadStoreSlot("UserLogger");

        userController.RegisterUser("KENAN", "12kdk3");

        _throttle.Release();
    });

    t1.Start();
    t2.Start();

    while (_throttle.CurrentCount != 2)
    {
        Thread.Sleep(1000);
    }

    Thread.FreeNamedDataSlot(Constants.APP_CONTEXT);
  }

  private static void InitializeThreadStoreSlot(string loggerName)
  {
      LocalDataStoreSlot threadDataStoreSlot = Thread.GetNamedDataSlot(Constants.APP_CONTEXT);

      IDictionary<string, object> threadAppContext = (IDictionary<string, object>)Thread.GetData(threadDataStoreSlot);

      if (threadAppContext == null)//it will be null for new Thread.
      {
          threadAppContext = new Dictionary<string, object>
          {
              [Constants.APP_START_TIME] = DateTime.UtcNow,
              [Constants.TOKEN] = Guid.NewGuid().ToString("N"),
              [Constants.THREAD_INFO] = Thread.CurrentThread.ManagedThreadId,
              [Constants.LOGGER] = new Logger(loggerName)
          };

          Thread.SetData(threadDataStoreSlot, threadAppContext);
      }
  }
}
Mono C# compiler version 4.0.4.0