我正在尝试使用 Event Tracing for Windows (ETW)在我的 .NET 应用程序中通过 EventSource .NET 4.5 中包含的类。我将 EventSource
子类化为 MyEventSource
并尝试实现接口(interface) IMyEventSource
(用于模拟目的),如下所示:
public interface IMyEventSource
{
void Test();
}
public class MyEventSource : EventSource, IMyEventSource
{
public static MyEventSource Log = new MyEventSource();
[Event(1)]
public void Test()
{
this.WriteEvent(1);
}
}
当我运行PerfView时并执行此代码,我在调用 WriteEvent
时收到 IndexOutOfRangeException
。如果我通过修改代码删除接口(interface)...
public class MyEventSource : EventSource
{
public static MyEventSource Log = new MyEventSource();
[Event(1)]
public void Test()
{
this.WriteEvent(1);
}
}
...然后一切正常。
这是我在这两种情况下用于测试的代码:
static void Main(string[] args)
{
MyEventSource.Log.Test();
}
如果我的 EventSource
子类只是实现了一个接口(interface),为什么它会中断?
这是一个related post .
最佳答案
在提出问题时,@LarsSkovslund 的答案是正确的。但是有了Microsoft.Diagnostics.Tracing.EventSource的稳定版本,微软changed this according to their blog post :
With the RTM release we’ve relaxed some of the event source validation rules in order to enable certain advanced usage scenarios.
The two changes in this area:
EventSource types may now implement interfaces to enable the use of event source types in advanced logging systems that use interfaces to define a common logging target.
The concept of a utility event source type (defined as an abstract class deriving from EventSource) is introduced to support sharing code across multiple event source types in a project (e.g. for optimized WriteEvent() overloads).
System.Diagnostics.Tracing.EventSource 随 .NET Framework 提供,自 .NET 4.6 起支持这些方案。
关于.net-4.5 - 为什么在 EventSource 的子类上实现接口(interface)会在运行时抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16301553/