C# async void in a button click handler, the exception just disappears?
Hello, I have a question to you. In my Ausbildung company we have a WinForms tool (yes WinForms xD). I made a button that loads customers from our internal API. When the API is down, nothing happens. No error, no MessageBox, the grid just stays empty. private async void btnLoad_Click(object sender, EventArgs e) { try { LoadData(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private async Task…
Accepted answer
Your Ausbilder is right, with one exception: event handlers. Their signature is fixed, so async void is allowed there and only there. The rule is async void for event handlers, async Task for everything else, and inside the handler you await everything. Your bug is one missing word. You call LoadData() without await. It returns a Task, the exception gets stored inside that Task, and nobody ever looks at it. Your try/catch finished before the request even failed. Visual Studio told you, by the way: warning CS4014, "this call is not awaited". private async void btnLoad_Click(object sender, EventArgs e) { btnLoad.Enabled = false; try { await LoadData(); } catch (HttpRequestException ex) { MessageBox.Show("API nicht erreichbar: " + ex.Message, "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { btnLoad.Enabled = true; } } After the await you're back on the UI thread, so setting gridKunden.DataSource is safe. Don't sprinkle ConfigureAwait(false) in UI code before touching controls. And set _http.Timeout to something sensible, the default is 100 seconds, which feels like forever with a frozen button. Last thing: turn on TreatWarningsAsErrors in the csproj. That warning list is a to-do list, not wallpaper.