相关疑难解决方法(0)

如何使用log4net使用Threadpool线程记录正确的上下文?

我试图找到一种从一堆线程中记录有用上下文的方法.问题是很多代码都是通过线程池线程到达的事件处理的(据我所知),因此它们的名称与任何上下文无关.可以使用以下代码演示此问题:

class Program
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    static void Main(string[] args)
    {
        new Thread(TestThis).Start("ThreadA");
        new Thread(TestThis).Start("ThreadB");
        Console.ReadLine();
    }

    private static void TestThis(object name)
    {
        var nameStr = (string)name;
        Thread.CurrentThread.Name = nameStr;
        log4net.ThreadContext.Properties["ThreadContext"] = nameStr;
        log4net.LogicalThreadContext.Properties["LogicalThreadContext"] = nameStr;
        log.Debug("From Thread itself");
        ThreadPool.QueueUserWorkItem(x => log.Debug("From threadpool Thread: " + nameStr));
    }
}
Run Code Online (Sandbox Code Playgroud)

转换模式是:

%date [%thread] %-5level %logger [%property] - %message%newline
Run Code Online (Sandbox Code Playgroud)

输出是这样的:

2010-05-21 15:08:02,357 [ThreadA] DEBUG LogicalContextTest.Program [{LogicalThreadContext=ThreadA, log4net:HostName=xxx, ThreadContext=ThreadA}] - From Thread itself
2010-05-21 15:08:02,357 [ThreadB] DEBUG LogicalContextTest.Program …
Run Code Online (Sandbox Code Playgroud)

c# log4net multithreading threadpool

11
推荐指数
2
解决办法
1万
查看次数

EndInvoke更改当前的CallContext - 为什么?

我有以下测试

[Test]
public void aaa()
{
    CallContext.LogicalSetData("aa", "1");

    Action parallelMethod = () => CallContext.LogicalSetData("aa", "2"); 
    var r = parallelMethod.BeginInvoke(null, null); 
    parallelMethod.EndInvoke(r);

    Assert.That(CallContext.LogicalGetData("aa"), Is.EqualTo("1")); 
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么这个测试在最后一行失败?

其实我知道为什么 - 因为EndInvoke正在将paraConll方法的CallContext合并到当前的方法 - 但我不明白这个的原因.

对我来说,这种行为类似于从方法内部更改方法参数值:-(

编辑:我已经将我的代码示例更改为仅使用LogicalGetData和LogicalSetData.正如您在我的其他问题中所看到的,我想将一些数据传递给另一个线程,但我没想到EndInvoke()会覆盖我在其他线程中更改的值.

.net multithreading

6
推荐指数
1
解决办法
1372
查看次数

标签 统计

multithreading ×2

.net ×1

c# ×1

log4net ×1

threadpool ×1