C#: async void vs async Task — why does my exception crash the app?

asked 2 months ago151 viewsen

1

An exception thrown in an async void method crashes my whole process instead of being caught by the caller's try/catch. Why?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 2 months ago

1 Answer

5
✓
✓ Accepted answer

An async void method returns nothing the caller can await, so the caller can't observe its exceptions. They're raised directly on the SynchronizationContext (or the thread pool), which usually crashes the process.

// ❌
async void SaveAsync() { await db.SaveChangesAsync(); }

// ✅
async Task SaveAsync() { await db.SaveChangesAsync(); }

Rules: - Always return Task or Task<T> (or ValueTask). - The only legitimate async void is an event handler (button.Click += async (s, e) => ...). Wrap its body in try/catch. - Enable the analyzer VSTHRD100 (Microsoft.VisualStudio.Threading.Analyzers) to flag it.

Sign in to tell others whether this worked.

answered 2 months ago

Sign in and verify your email to post an answer.