C#: async void vs async Task — why does my exception crash the app?
poze 2 months ago148 gadeen
An exception thrown in an async void method crashes my whole process instead of being caught by the caller's try/catch. Why?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.