c# - .Net Task class - please explain -
can please explain why public async task dostuff() method below can still work without returning anything? doesn't void, assumed return type have task.
when remove async , await keywords dostuff() method, compiler gives me "not code paths return value" error. however, if add async , await keywords, doesn't seem need return type, despite lack of void keyword in method signature. don't it!
what task? microsoft explains poorly. thanks.
namespace async_and_await_example { class program { static void main(string[] args) { asyncawaitdemo demo = new asyncawaitdemo(); demo.dostuff(); (int = 0; < 100; i++) { console.writeline("working on main thread..................."); } } } public class asyncawaitdemo { public async task dostuff() { await task.run(() => { counttofifty(); }); } private static async task<string> counttofifty() { int counter; (counter = 0; counter < 51; counter++) { console.writeline("bg thread: " + counter); } return "counter = " + counter; } } }
why public async task dostuff() method below can still work without returning anything?
because compiler allows to. when mark method async modifier, state-machine created returns task you. can see in de-compiler.
when remove async , await keywords dostuff() method, compiler gives me "not code paths return value" error.
because there no longer state machine created returns task, have now, since there no more compiler magic.
what task?
as others said, promise of work complete in future. task can represent many things, 1 of them asynchronous operation. magic lays async-await keywords come alongside. compiler magic has special relationship task, type implementing getawaiter method can awaited. more on here
Comments
Post a Comment