我每秒生成超过100条消息,并在单独的线程中发送这些消息。当连接断开时,我想在调用者中捕获异常。由于我的所有消息都是异步发送的,因此我无法捕获异常。
以下是调用DispatcherTimer
方法
dispatcherTimer_Tick
代码
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;
}
答案 0 :(得分:1)
事件处理程序是允许async 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
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);
}
}