log4net上下文设置。如何将上下文传播给Task并行库产生的子线程

时间:2018-11-30 11:04:30

标签: c# .net log4net

我正在使用以下代码来设置log4net上下文

 public static IDisposable ThreadContextSet(string key, object value)
        {
            //object oldVal = ThreadContext.Properties[key];
            ThreadContext.Properties[key] = value;
            var topMostCleaner = new DispCleaner();
            topMostCleaner.EvDispose += () => {
                // Pop = restore old value
                //ThreadContext.Properties[key] = oldVal;
                ThreadContext.Properties[key] = null;
            };
            return topMostCleaner;
        }

        private class DispCleaner : IDisposable
        {
            public event Action EvDispose;

            public void Dispose()
            {
                if (EvDispose != null)
                {
                    EvDispose();
                }
            }
        }

问题是当我从方法创建子线程时,上下文没有转移到那些线程。

public void InitiateTransaction(InitiateTransactionRequest info)
{
..
...
                using (Log4NetExt.ThreadContextSet(StringConstants.Log4NetContextConstants.Ip, this.RequestIp))
                using (Log4NetExt.ThreadContextSet(StringConstants.Log4NetContextConstants.TransactionMsisdn, msisdn))
                using (Log4NetExt.ThreadContextSet(StringConstants.Log4NetContextConstants.TransactionId, transactionId))
                {

                ...
                ....

                Task.Factory.StartNew(() => ProcessTransactionAync()); // context not transfer
                }

}

有人可以帮我吗

1 个答案:

答案 0 :(得分:1)

我已将代码从ThreadContext.Properties更改为LogicalThreadContext.Properties 看起来像是在工作

解决方案的参考链接为Conflict between Log4Net's ThreadContext and Task