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
using System;
using System.Collections.Generic;
using System.Threading;

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

  public static void Main (string[] args) {

    InitializeThreadStatic("ApplicationLogger");

    UserController userController = new UserController();

    ProductController productController = new ProductController();

    productController.SetOutofStock("6035");

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

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

        productController.SetOutofStock("1002");

        _throttle.Release();
    });

    _throttle.Wait();
    Thread t2 = new Thread(() =>
    {
        InitializeThreadStatic("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 InitializeThreadStatic(string loggerName)
  {
    if (ApplicationContext.Values == null)//it will be null for new Thread.
    {
        ApplicationContext.Values = new Dictionary<string, object>
        {
            [Constants.APP_START_TIME] = DateTime.UtcNow,
            [Constants.TOKEN] = Guid.NewGuid().ToString("N"),
            [Constants.THREAD_INFO] = Thread.CurrentThread.ManagedThreadId
        };
    }

    if (ApplicationContext.Logger == null)//it will be null for new Thread.
    {
        ApplicationContext.Logger = new Logger(loggerName);
    }
  }
}
Mono C# compiler version 4.0.4.0