Rollbar .NET API:如何等待所有待处理的异步消息完成?

Rollbar .NET API: How to wait until all pending async messages have completed?

我有一个 .NET 控制台应用程序,它使用 official Rollbar .NET API 到 post 将消息异步记录到 Rollbar。用于发送每条消息的 C# 代码如下所示:

RollbarLocator.RollbarInstance.Log(ErrorLevel.Error, "test message");

我注意到,如果我的应用程序在发送异步消息后不久终止,则该消息通常不会到达 Rollbar —— 显然是因为消息在终止时仍处于挂起状态。

如果我的应用程序在退出前休眠几秒钟,通常成功发送所有未决消息:

// Give outgoing async Rollbar messages time to send before we exit.
System.Threading.Thread.Sleep(6000);

但是,显然,这种方法并不是非常优雅。

文档做 briefly touch on this situation:

However, in some specific situations (such as while logging right before exiting an application), you may want to use a logger fully synchronously so that the application does not quit before the logging completes (including subsequent delivery of the corresponding payload to the Rollbar API).

但是,在我的场景中,我不一定知道在我记录给定消息时程序是否即将退出。

可以记录一个调试级别的“现在退出!”在程序终止之前同步消息;但是,从文档中不清楚这样做是否会导致任何未决的异步消息也被发送?

有没有一种优雅的方法来保证所有发送到 Rollbar 的未决异步消息在我的程序终止之前实际上已经发送(或超时)?

在这种情况下,您需要使用阻塞记录器。例如:

RollbarLocator.RollbarInstance
   .AsBlockingLogger(TimeSpan.FromSeconds(6))
   .Log(ErrorLevel.Error, "test message");

更多详情,请看这里: https://docs.rollbar.com/docs/basic-usage#blocking-vs-non-blocking-logging