如何使用 Application Insight 的持久性通道防止丢失遥测事件?

How to prevent losing telemetry events with Application Insight's Persistence Channel?

我已将 Microsoft Application Insights 集成到我的 Windows Forms 应用程序中。在使用默认内存通道的文档Application Insights on Windows Desktop apps, services and worker roles中,刷新后应用程序在退出前休眠一秒钟。

 tc.Flush(); // only for desktop apps

 // Allow time for flushing:
 System.Threading.Thread.Sleep(1000);

文档指出:

Note that Flush() is synchronous for the persistence channel, but asynchronous for other channels.

由于这个例子使用的是内存通道,我可以推断代码示例中的刷新是异步的,因此是睡眠。

在我的代码中,我使用了持久性通道。就在退出我的程序之前,我引发了一个事件 Application Shutdown:

static void Main(string[] args)
{
    try { /* application code */ }
    finally
    {
        Telemetry.Instance.TrackEvent("Application Shutdown");
        Telemetry.Instance.Flush();
        System.Threading.Thread.Sleep(1000); // allow time for flushing
    }
}

根据文档,Flush 是同步的,因此在应用程序退出之前不需要睡眠。查看到达 Azure 门户的事件,我可以看到对于大多数用户来说 Application Shutdown 事件没有到达云中。单步调试,跨过Flush我也感觉不到任何延迟。

我确定我使用了持久性通道,因为我可以看到数据缓冲在 %LOCALAPPDATA%\Microsoft\ApplicationInsights

我的问题是:

如果我没记错的话,Flush() 会将剩余的遥测数据同步写入缓冲区(在持久通道的情况下为 %LOCALAPPDATA%),但它不会启动任何传递操作。如果缓冲区位置没有改变,我希望此遥测稍后会在下一个应用程序启动时显示,因为 AI 将读取缓冲数据并将其发送出去。 我在这里可能弄错了,这背后的逻辑可能在不久前就已经改变了..