c# - How to Properly Call an Await Method in Main? -
using system; using system.collections.generic; using system.io; using system.linq; using system.text; using system.threading.tasks; namespace taskconsole { class program { static void main(string[] args) { test(); } static async task<string> readtextasync() { string textcontents; task<string> readfromtext; using (streamreader reader = file.opentext("email.txt")) { readfromtext = reader.readtoendasync(); textcontents = await readfromtext; } return textcontents; } static async task test () { string capture = await readtextasync(); console.writeline(capture); } } }
i have following code read text file using async. learned post example microsoft implemented using streamreader incorrect, learning exercise, decided correct it. how call test method main, when test method doesn't return task. did little reading , learned it's bad practice use async void. in case should do?
side note: don't know if implemented wrong, can't text display. tried non-async way , worked, however, when use async shows blank, , please press key continue"
how call test method main, when test method doesn't return task.
because main
can't modified async
, you'll have explictly call task.wait
on it:
test().wait();
this only place should blocking on async call.
Comments
Post a Comment