Reputation: 21
I'm struggling weird problem that occurred only in debug mode on Windows 7.
I'm try to catch exception that I'm throwing in method delcared async
. Yes, I'm awaiting it, but exception still stands uncaught in inner function. See code below.
private void Connect(int port)
{
lock (apiLocker)
{
if (port <= 0)
{
throw new ArgumentException("Invalid port number");
}
//etc.
}
}
internal async Task ConnectAsync(int port)
{
await Task.Run(() =>
{
Connect(port);
});
}
And invoke looks like this:
private async Task<bool> ConnectAsync()
{
try
{
await RadioDispatcher.Instance.ConnectAsync(connectionSettings.Port);
return true;
}
catch
{
//I can't reach that line in Debug on windows 7.
//In Release on Windows 10 it works fine.
return false;
}
}
Upvotes: 1
Views: 86
Reputation: 456717
TL;DR: This is a quirk of Visual Studio debugging. Just hit Continue when the exception is thrown, and it'll be caught.
More detail:
The way async
methods work is that the async
state machine catches the exception and places it on the returned Task
. Later, when your code await
s that Task
, the exception is extracted and re-thrown.
However, Visual Studio has special debugging logic that sees that the exception is caught after it has left your code and kind of freaks out, thinking that your code has neglected catching that exception. VS does not understand that the exception is stored and will be observed later. So that's why you see an "unhandled exception" message.
Side note: creating asynchronous wrappers for synchronous methods is an anti-pattern.
Upvotes: 1