C# 多重异步方法调用期间的异常处理无效
我每秒生成100多条消息,并在单独的线程中发送这些消息。当连接断开时,我想捕获调用方中的异常。因为我所有的消息都是异步发送的,所以我无法捕获异常 下面是调用Dispatchermer_Tick方法的Dispatchermer代码 这是SendMessage代码。我根据以下内容进行了修改:,但它不起作用C# 多重异步方法调用期间的异常处理无效,c#,multithreading,mqtt,C#,Multithreading,Mqtt,我每秒生成100多条消息,并在单独的线程中发送这些消息。当连接断开时,我想捕获调用方中的异常。因为我所有的消息都是异步发送的,所以我无法捕获异常 下面是调用Dispatchermer_Tick方法的Dispatchermer代码 这是SendMessage代码。我根据以下内容进行了修改:,但它不起作用 private async static Task SendMessage(string message) { try { (MQTT.RunAsync(messa
private async static Task SendMessage(string message)
{
try
{
(MQTT.RunAsync(message.ToString(), topic)).Wait();
}
catch (Exception Ex)
{
// Exceptions are not getting cought here
}
}
MQTT.RunAsync的定义
及
事件处理程序是允许异步void的例外
private async void dispatcherTimer_Tick(object sender, EventArgs e) {
try {
item = "some generated message";
await SendMessage(item);
} catch (Exception ex) {
//...handle exception
}
}
此外,您似乎正在以任何方式使用异常,因为它已经被捕获到堆栈的更深处
尽量使代码始终保持异步,不要混合使用.Wait或.Result之类的阻塞调用
您是否尝试在MQTT.RunAsync中从RunAsync引发异常?是的,这会中断应用程序。我写了,抛出异常。我觉得AppDomain.UnhandledException事件是解决方案。看起来不错,但我的RunAsync并不简单。我现在对整个RunAsync方法提出了质疑。我无法在RunAsync内部使用return进行连接检查。即使连接检查也可能抛出异常,直到它不抛出异常!断然的。我们不应放置try-catch:并需要使用TaskScheduleRonUnobservedTaskeException处理程序:
public static async Task RunAsync(string message)
{
var mqttClient = factory.CreateMqttClient()
try
{
await mqttClient.ConnectAsync(options);
}
catch (Exception exception)
{
}
}
Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
public Task RunAsync(string message, string topicName)
{
this.mqttClient.ConnectAsync(this.options);
mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(this._topicname).WithExactlyOnceQoS().Build());
var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(this._topicname)
.WithPayload(message).WithAtLeastOnceQoS().Build();
if (stopSending == false)
{
return mqttClient.PublishAsync(applicationMessage);
}
return null;
}
private async void dispatcherTimer_Tick(object sender, EventArgs e) {
try {
item = "some generated message";
await SendMessage(item);
} catch (Exception ex) {
//...handle exception
}
}
private static Task SendMessage(string message) {
return MQTT.RunAsync(message, topic);
}
public static async Task RunAsync(string message, string topicName) {
await this.mqttClient.ConnectAsync(this.options);
var topicFilter = new TopicFilterBuilder().WithTopic(this._topicname)
.WithExactlyOnceQoS().Build();
await mqttClient.SubscribeAsync(topicFilter);
var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(this._topicname)
.WithPayload(message).WithAtLeastOnceQoS().Build();
if (stopSending == false) {
await mqttClient.PublishAsync(applicationMessage);
}
}