Conflict between Log4Net's ThreadContext and Task

柔情痞子 提交于 2019-12-10 13:58:01

问题


Has anyone tried to stack contexts and use Tasks at the same time?

I'm trying something like this:

using (log4net.ThreadContext.Stacks["contextLog"].Push("Saving Data"))
{
    log.Info("Starting transaction");
    var taskList = new List<Task>();
    taskList.Add(Task.Factory.StartNew(() =>
    {
        log.Info("Inside Transaction");
    }));
    Task.WaitAll(taskList.ToArray());
}

and I'm getting that result:

2015/42/26 13:42:10,841 INFO  [Saving Data] Starting transaction
2015/42/26 13:42:10,870 INFO  [(null)] Inside Transaction

I was expecting it to have [Saving Data] instead of [(null)] on the second line.

It appears to lose access to the log4net ThreadContext Stack as soon as it starts a new Task.

Do you know how to avoid this?

EDIT: At first o thought is was a problem with Transaction Scope, but as @stuartd pointed me, it was working fine. Then I realized that there was a task and that was the real problem.


回答1:


The task will run on a different thread so the data in the ThreadContext stack isn't available, you should use the log4net.LogicalThreadContext instead as data in that should follow the logical execution and still be visible to the Task



来源:https://stackoverflow.com/questions/32233419/conflict-between-log4nets-threadcontext-and-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!