如何将用户定义的对象序列化为WriteEvent
本文关键字:对象 序列化 WriteEvent 定义 用户 | 更新日期: 2023-09-27 18:25:34
在MSDN文档中,Write事件仅支持int和字符串参数类型。我想传递一个用户创建的ct-to-Write事件,如何获得此功能?什么是实现此功能的正确序列化程序?
有几个选项:
- 按照magicandre1981的建议使用新的.NET 4.6功能。除非你必须使用.NET 4.5、4.0甚至3.5,否则这是最好的选择
- 手动将它们序列化为JSON或Bond等
- 手动创建
EventData
结构并传递给WriteEventCore
(必须在unsafe
内部)-TPL当前使用此方法 - 或者你可以举个例子。有一篇关于这个的博客文章
在Windows 10(也可后移植到Win7/8.1)中,自.Net 4.6:以来,就支持Rich Payload Data
// define a ‘plain old data’ class
[EventData]
class SimpleData {
public string Name { get; set; }
public int Address { get; set; }
}
[EventSource(Name = "Samples-EventSourceDemos-RuntimeDemo")]
public sealed class RuntimeDemoEventSource : EventSource
{
// define the singleton instance of the event source
public static RuntimeDemoEventSource Log = new RuntimeDemoEventSource();
// Rich payloads only work when the self-describing format
private RuntimeDemoEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { }
// define a new event.
public void LogSimpleData(string message, SimpleData data) { WriteEvent(1, message, data); }
}
RuntimeDemoEventSource.Log.LogSimpleData(
"testMessage",
new SimpleData() { Name = "aName", Address = 234 });
阅读博客和文档了解更多详细信息。