3

如何从同一应用程序的两个实例写入同一文件。对于写入,我使用了来自 System.Diagnostis 命名空间的 TraceSource 类和 TraceEvent 方法。我尝试使用 Mutex 创建方法进行写入,但我的方法无法正常工作。我找不到使用互斥锁进行 TraceSource 日志记录的示例。有谁能够帮我?

我的日志类:

public class LoggerTraceSource
 {
   private readonly TraceSource traceSource = new TraceSource();

  public void InfoTraceEvent(string message, int level)
        {
            traceSource.TraceEvent(TraceEventType.Information, level, message);
        }
 }

在我的应用程序中,我使用 InfoTraceEvent 写入日志文件。如何更改 InfoTraceEvent 以进行线程写入(由两个应用程序实例写入)?

4

1 回答 1

0

I'm doing some ESP diagnostics here because I don't know what the symptoms are. I'm guessing you have process1.exe and process2.exe each with identical system.diagnostics sections, i.e. writing to the same file.

As soon as process1.exe starts writing to the trace file, it holds a lock for the duration of the process. When process2.exe tries to write to the same file, it will machine generate a name for a new file, like file13.txt

This behavior can vary depending on the listener. For example, if you write a custom listener that blocks on attempts to write to a locked file, then you'd see that behavior.

I'd recommend either writing to 2 different files or using a custom listener that closes the file handle after each write. This would require doing re-tries when the two processes happen to try to open the file simultaneously.

于 2014-07-29T14:19:33.350 回答