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

posée 2 months ago151 vuesen

1

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 2 months ago

1 réponse

5
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 2 months ago

Sign in and verify your email to post an answer.