我尝试使用Visual Studio探查器分析应用程序,以查看潜在的线程争用问题,但问题是探查器将等待信号视为最严重的违规行为(因为消费线程大部分时间都在等待信号),而实际上,在产生端看到争用会更有趣。
E、 例如,我正在为log4net使用一个异步appender,以减少日志记录对实际工作人员的影响,它基本上是一个包装器
BlockingCollection<T>
:
readonly BlockingCollection<LoggingEventContext> _queue;
protected override void Append(LoggingEvent e)
{
// instead of appending, push to the queue
_queue.Add(new LoggingEventContext(e, HttpContext), _loggingCancelationToken);
}
void StartForwarding()
{
_queue = new BlockingCollection<LoggingEventContext>(BufferSize);
_loggingCancelationTokenSource = new CancellationTokenSource();
_loggingCancelationToken = _loggingCancelationTokenSource.Token;
_loggingTask = new Task(SubscriberLoop, _loggingCancelationToken);
_loggingTask.Start();
}
void SubscriberLoop()
{
try
{
// this is the blocking call which is reported as the source of contention
foreach (var entry in _queue.GetConsumingEnumerable(_loggingCancelationToken))
{
HttpContext = entry.HttpContext;
ForwardLoggingEvent(entry.LoggingEvent, ThisType);
}
}
catch (OperationCanceledException ex)
{
...
}
catch (ThreadAbortException ex)
{
...
}
}