C# 使用异步时,调用方未接收到异常
我正在使用C# 使用异步时,调用方未接收到异常,c#,multithreading,asynchronous,exception-handling,async-await,C#,Multithreading,Asynchronous,Exception Handling,Async Await,我正在使用dispatchermer以指定的时间间隔处理方法 dispatcherTimer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 1, 0) }; dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 以下是Dispatchermer\u Tick方法 private void dispatcherTimer_Tick(object
dispatchermer
以指定的时间间隔处理方法
dispatcherTimer = new DispatcherTimer()
{
Interval = new TimeSpan(0, 0, 0, 1, 0)
};
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
以下是Dispatchermer\u Tick
方法
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
Task.Run(() => MethodWithParameter(message));
}
catch (Exception ex)
{
}
}
我在这里调用MQTTPublisher
,这是一个DLL引用
private async static void MethodWithParameter(string message)
{
try
{
await MQTTPublisher.RunAsync(message);
}
catch (Exception Ex)
{
}
}
我无法捕获在该DLL中抛出的异常。我怎样才能获得呼叫方的异常
RunAsync的定义-这在单独的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 ConnectAsync(IMqttClientOptions)
这是使用async
void的缺点。更改方法以返回异步任务
:
private async static Task MethodWithParameter(string message)
{
try
{
await MQTTPublisher.RunAsync(message);
}
catch (Exception Ex)
{
}
}
基于:
异步void方法具有不同的错误处理语义。当从异步任务或异步任务方法抛出异常时,将捕获该异常并将其放置在任务对象上。对于异步void方法,没有任务对象,因此从异步void方法抛出的任何异常都将直接在异步void方法启动时处于活动状态的SynchronizationContext上引发
以及:
图2使用Catch无法捕获异步Void方法的异常
对于初学者,如果每次有人使用
async-void
时,微软可能会按下一个按钮来伤害编码者,请不要使用async-void
。事实上,我相信大多数用户也会这么做。还有什么是RunAsync()?RunAsync是一个方法名。它可以是任何名称。有更好的解决方案吗?向我们展示该方法的定义,不要将其作为注释:)@general事件方法上只允许使用async void
。否则是,请使用该死的异步任务
!
private async static Task MethodWithParameter(string message)
{
try
{
await MQTTPublisher.RunAsync(message);
}
catch (Exception Ex)
{
}
}
private async void ThrowExceptionAsync()
{
throw new InvalidOperationException();
}
public void AsyncVoidExceptions_CannotBeCaughtByCatch()
{
try
{
ThrowExceptionAsync();
}
catch (Exception)
{
// The exception is never caught here!
throw;
}
}