c# - Can you explain why the exception is not caught if I do not await an async task? -
starting issue had on code, i've created simple app recreate problem:
private async void button1_click(object sender, eventargs e) { task task = task.run(() => { testwork(); }); try { await task; messagebox.show("exception uncaught!"); } catch (exception) { messagebox.show("exception caught!"); } } private async void button2_click(object sender, eventargs e) { task task = testwork(); try { await task; messagebox.show("exception uncaught!"); } catch (exception) { messagebox.show("exception caught!"); } } private async task testwork() { throw new exception(); } the code button1_click not catch exception. i've verified because i'm not awaiting testwork async method. indeed i've warning message visual studio inform me i'm not awaiting method. solution compile , i'm scared can happen somewhere else in code if use extensively async/await. can please explain reason , peraphs give golden rule avoid it?
p.s.: works if in code button1_click write:
task task = task.run(async () => { await testwork(); });
in first button1_click implementation, ignoring result of task returned testwork.
in modified version, await checks exception , propogates catch.
in fact, compiler warning seeing important. if testwork ran on different thread, because wrapper task in first implementation doesn't wait testwork complete, complete testwork had started.
writing way makes clearer:
task task = task.run( () => { task t = testwork(); // ignore t } );
Comments
Post a Comment