Log4Net的ThreadContext和Task之间的冲突 [英] Conflict between Log4Net's ThreadContext and Task

查看:93
本文介绍了Log4Net的ThreadContext和Task之间的冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人尝试同时堆叠上下文并使用Tasks吗?

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());
}

我得到的结果是:

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

我希望它的第二行具有 [保存数据] ,而不是 [(null)] .

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

它似乎一开始启动新Task就失去对log4net ThreadContext堆栈的访问权限.

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?

起初,我认为这是Transaction Scope的问题,但是正如@stuartd指出的那样,它工作正常.然后我意识到有一个任务,那才是真正的问题.

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.

推荐答案

该任务将在其他线程上运行,因此ThreadContext堆栈中的数据不可用,您应该使用log4net.LogicalThreadContext代替应该遵循逻辑执行,并且仍然对Task

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

这篇关于Log4Net的ThreadContext和Task之间的冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆