c# - async/await approach for Fire and Forgot -
this question has answer here:
let's have following code in winforms app.
private async task<decimal> divasync(int a, int b) { await taskex.delay(2000); return / b; } private async task divasyncwitherrorhandling(int a, int b) { try { await divasync(a, b); } catch (dividebyzeroexception) { debug.writeline("divasync({0}, {1}) failed", a, b); } } private void button1_click(object sender, eventargs e) { divasyncwitherrorhandling(5, 0); } private void button2_click(object sender, eventargs e) { taskex.run(() => divasyncwitherrorhandling(5, 0)); } private async void button3_click(object sender, eventargs e) { await divasyncwitherrorhandling(5, 0); await somethingelse(); }
obviously real word code else. point is, have error handling. code divasyncwitherrorhandling
may run await
(see example button3_click
) can not use async void
approach may run fire , forgot.
button1_click
, button2_click
both produce excepted result (divasyncwitherrorhandling
run asynchronous without blocking ui differt advantages / disadvantages.
button1_click
shows warning because call not awaited, execution ... continues before call complete.
has less code
button2_click
not show warning, has more code write , uses task.
so question is. best solution in case? ignore warning , use button1
or use button2
.
maybe there better solution buildin similar task.runsynchronously
fire , forgot.
divasyncwitherrorhandling(5, 0).runasynchronously();
the purpose convert "old style" routine takes optional action continue after completion async/await pattern
private divasyncwitherrorhandlingold(int a, int b, action after = null) { task.factory.startnew(() => { try { div(a, b); } catch (dividebyzeroexception) { debug.writeline("divasync({0}, {1}) failed", a, b); } after?.invoke(); }); }
go task.run since it's more obvious going on , it's recommended approach.
"the run methods preferred way create , start tasks when more control on creation , scheduling of task not needed." source: https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming
"if work have cpu-bound , care responsiveness, use async , await spawn work off on thread task.run." source: https://docs.microsoft.com/en-us/dotnet/csharp/async
Comments
Post a Comment