What's the difference between log4net.ThreadLogicalContext and log4net.ThreadContext

前端 未结 2 1715
陌清茗
陌清茗 2021-01-22 23:28

I don\'t understand the explanation in offical document:

Logical threads can jump from one managed thread to another.

What\'s the different between Thre

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 00:08

    From using this myself, I see the benefit of using the ThreadLogicalContext when working with multi threaded logic (async, await).

    For example, if you set the property on your original calling thread using ThreadContext, it is also available to any other tasks that get to run on the same thread.

    // caller thread (thread #1)
    log4net.ThreadContext.Properties["MyProp"] = "123"; // now set on thread #1
    log("start");
    await Task.WhenAll(
      MyAsync(1), // `Issue` if task run on thread #1, it will have "MyProp"
      MyAsync(2)  // `Issue` if task run on thread #1, it will have "MyProp"
    );
    log("end"); // `Issue` only by random chance will you run on thread #1 again
    

    Where as if you use ThreadLogicalContext, it stays on the calling context.

    // caller thread (thread #1)
    log4net.LogicalThreadContext.Properties["MyProp"] = "123"; // now set on calling context
    log("start");
    await Task.WhenAll(
        MyAsync(1), // if task run on thread #1, there is no "MyProp"
        MyAsync(2)  // if task run on thread #1, there is no "MyProp"
    );
    log("end"); // if task run on thread #1, there is no "MyProp"
    

    With await you are never guaranteed you come back to the same thread as when you started and the calling context will have changed, so you will have to set the property again.

    ...
    log4net.LogicalThreadContext.Properties["MyProp"] = "123";
    log("end");
    

提交回复
热议问题