【发布时间】:2022-08-04 21:12:55
【问题描述】:
我在下面有这段代码,可以将消息发送到 azure EventHub,起初它工作正常
public async Task SendMessage(string message) {
var producer = new EventHubProducerClient(this.connectionString, this.eventHubName);
using (EventDataBatch eventBatch = await producer.CreateBatchAsync()) {
if (!eventBatch.TryAdd(new EventData(message))) {
throw new Exception($\"Event is too large for the batch and cannot be sent.\");
}
try {
await producer.SendAsync(eventBatch);
}
catch(Exception ex) {
saveLog(message, ex);
}
finally {
await producer.DisposeAsync();
}
}
}
但在 Application Insights 中,我正面临此消息异常:
等待任务也未观察到任务的异常 或访问其 Exception 属性。结果,未观察到 终结器线程重新抛出异常。连接尝试 失败,因为连接方没有正确响应后 一段时间,或建立连接失败,因为已连接 主持人未能回应
异常类型:
System.Net.Sockets.SocketException
我尝试添加一个 ContinueWith(OnlyOnFaulted 或 OnlyOnCanceled),如下所示,以记录它, 但现在我进入了 catch Exception (不在 ExceptionHandle 中)作为“任务已取消”
try { await producer.SendAsync(eventBatch) .ContinueWith(t => ExceptionHandle(t, message), TaskContinuationOptions.OnlyOnFaulted); }如何处理 App Insights 显示的这些异常?
-
我认为我们没有足够的代码来提供想法。您显示的内容等待所有异步调用(假设
saveLog不是异步的)您的SendMessage是如何调用的? -
我也强烈建议不要使用您在这里使用的模式;生产者客户端旨在创建一次并在应用程序的整个生命周期中用作单例。为您要发送的每条消息创建一个新客户端会给 GC 带来不必要的压力并且性能不佳。对单个消息使用批处理也没有任何好处。
标签: c# async-await azure-application-insights azure-eventhub