使用ASYNC时在调用方中未收到异常 [英] Exceptions are not received in caller when using ASYNC
问题描述
我正在使用DispatcherTimer
在指定的时间间隔内处理方法
I am using DispatcherTimer
to process a method at a specified interval of time
dispatcherTimer = new DispatcherTimer()
{
Interval = new TimeSpan(0, 0, 0, 1, 0)
};
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
这是dispatcherTimer_Tick
方法
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
Task.Run(() => MethodWithParameter(message));
}
catch (Exception ex)
{
}
}
在这里,我正在调用MQTTPublisher
,这是一个DLL参考.
Here I am calling MQTTPublisher
which is a DLL reference.
private async static void MethodWithParameter(string message)
{
try
{
await MQTTPublisher.RunAsync(message);
}
catch (Exception Ex)
{
}
}
我无法捕获该DLL中引发的异常.如何获得呼叫者的例外?
I am not able to catch the exceptions which are thrown in that DLL. How can I get exception to caller?
RunAsync的定义-这在单独的dll中.
Definition of RunAsync - This is in separate dll.
public static async Task RunAsync(string message)
{
var mqttClient = factory.CreateMqttClient();
//This creates MqttFactory and send message to all subscribers
try
{
await mqttClient.ConnectAsync(options);
}
catch (Exception exception)
{
Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
throw exception;
}
}
还有
Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
推荐答案
这是使用async
void的缺点.更改方法以返回async Task
代替:
This is the downside of using async
void. Change your method to return async Task
instead :
private async static Task MethodWithParameter(string message)
{
try
{
await MQTTPublisher.RunAsync(message);
}
catch (Exception Ex)
{
}
}
异步void方法具有不同的错误处理语义.从异步Task或异步Task方法抛出异常时,将捕获该异常并将其放置在Task对象上.使用异步void方法时,没有Task对象,因此从异步void方法抛出的任何异常都将直接在启动异步void方法时处于活动状态的SynchronizationContext上引发.
Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.
并且:
图2无法捕获到来自异步无效方法的异常
Figure 2 Exceptions from an Async Void Method Can’t Be Caught with Catch
private async void ThrowExceptionAsync()
{
throw new InvalidOperationException();
}
public void AsyncVoidExceptions_CannotBeCaughtByCatch()
{
try
{
ThrowExceptionAsync();
}
catch (Exception)
{
// The exception is never caught here!
throw;
}
}
这篇关于使用ASYNC时在调用方中未收到异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!