I have an action trigged by a button that should cover every possible cases.
private async void btnStart_Click(object sender, EventArgs e)
{
try
{
btnStart.Enabled = false;
await Task.Delay(1000);
btnStart.Visible = false;
btnStop.Visible = true;
var maxSessions = numericFieldSessions.Value;//to run the same stuff in parallell
for (var i = 0; i < maxSessions; i++)
{
await Task.Run(() =>
{
Parallel.Invoke(async () =>
{
while (true)
{
try
{
A();
await Task.Run(() => { B(); }); //longer operation
}
catch (CustomExceptionA ex)
{
DoLog($"Custom Exception A: {ex.Message}");
}
catch (CustomExceptionB ex)
{
DoLog($"Custom Exception B: {ex.Message}");
}
catch (CustomExceptionC ex)
{
DoLog($"Custom Exception C: {ex.Message}");
}
catch (Exception ex)
{
DoLog($"Generic Exception: {ex.Message}");
}
}
});
});
}
}
catch (Exception ex)
{
DoLog($"Full Generic Exception: {ex.Message}");
}
}
DoLog()
only writes the string to a File.
After a long time, the program just crash. Without logging anything. I saw in the Windows Event Log that an unhandled exception was thrown inside the method B()
. But B()
itself should not handle errors... and it isn't!
This is the log:
System.Runtime.InteropServices.ExternalException
em System.Drawing.Image.FromHbitmap(IntPtr, IntPtr)
em System.Drawing.Image.FromHbitmap(IntPtr)
em System.Drawing.Icon.BmpFrame()
em System.Drawing.Icon.ToBitmap()
em System.Windows.Forms.ThreadExceptionDialog..ctor(System.Exception)
em System.Windows.Forms.Application+ThreadContext.OnThreadException(System.Exception)
em System.Windows.Forms.Control.WndProcException(System.Exception)
em System.Windows.Forms.Control+ControlNativeWindow.OnThreadException(System.Exception)
em System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
And right after this error event there is another (in the same second):
Faulting application name: MyApp.exe, version: 1.0.0.0, timestamp: 0xb5620f2c
Faulty module name: KERNELBASE.dll, version: 10.0.18362.476, timestamp: 0x540698cd
Exception code: 0xe0434352
Fault offset: 0x001135d2
Failed process ID: 0xf54
Failed application start time: 0x01d5da61843fe0f8
Faulting application path: PATH_TO_MY_APP.exe
Faulting module path: C:\Windows\System32\KERNELBASE.dll
Report ID: 120a68ca-a077-47a4-ae62-213e146956a6
Failed package full name:
Application ID for the failed package:
How to prevent this? I thought that every exception would be handled.. how to prevent this? Assuming that - anything that happens inside B()
should be handled outside it?