【发布时间】:2018-06-09 12:29:17
【问题描述】:
我每秒生成超过 100 条消息,并在单独的线程中发送这些消息。当连接断开时,我想在调用者中捕获异常。由于我的所有消息都是异步发送的,因此我无法捕获异常。
这是调用dispatcherTimer_Tick方法的DispatcherTimer代码
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
item = "some generated message";
Task.Run(() => SendMessage(item));
}
catch (Exception)
{
}
}
这是SendMessage 代码。我通过阅读基于:Async/Await - Best Practices in Asynchronous Programming 进行了更改,但它不起作用
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 的定义
public static async Task RunAsync(string message)
{
var mqttClient = factory.CreateMqttClient()
try
{
await mqttClient.ConnectAsync(options);
}
catch (Exception exception)
{
}
}
还有
Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
更新问题
我的RunAsync 首先尝试连接,如果成功则发送消息。所以我不能在连接检查时写return。
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;
}
【问题讨论】:
-
您是否尝试过在 MQTT.RunAsync 中从 RunAsync 抛出异常?
-
是的,这会破坏应用程序。我写道,抛出异常。
-
我觉得 AppDomain.UnhandledException 事件是解决办法。
标签: c# multithreading mqtt