简体   繁体   中英

How to multi-thread “Cross-tier” a singleton with a correlation id without locking?

So we are using a common state context singleton with a correlation ID for centralized Logging. The purpose is to track the id throughout our entire process and correlate the different tiers.

The state context is accessed by multiple dlls and multiple users.

The difficulty comes when multi threading comes into play:

  1. Process 1 has fired by user 1
  2. Correlation ID gets set to {1}
  3. DLL A accesses state context and gets correlation ID {1}
  4. Before process 1 is completed, Process 2 has fired by user 2
  5. Correlation ID gets set to {2}
  6. DLL B from 1st process access state context with correlation id {2} when it should be {1}

How do we solve this issue?

We do not perceive locking to be our solution? Any other ideas?

Here is a diagram

        (S)->[  CorrelationID {get;set}  ]                  
               ^           ^            ^
    U1 <-->    |           |            |                 O  
    U2 <--> [DLLA] <-->  [DLLB] <-->  [DLLC]       <-->  | |
    U3 <-->         
            {Web}  <--> {Domain} <-> {Data Access} <--> {DB}

    (<--                 Process / Thread           -->    )  

{} = Examples of possible DLLs

Each User's process should have 1 correlation ID

After much research we have found the solution.

We utilize the LogicalCallContext Class in the .Net Framework

So what the LogicalCalContext Class does is it utilizes the .Net Framework, it keeps the Key Values in the pool by preserving the callback, even if it jumps thread.

Learn how to Flow Data across threads...

Approach for tying all NLog logs back to the original request within WebAPI

The comment in the post references Serilog as well so you might want to take a look at that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM