简体   繁体   中英

How to run loop async in c#

Lets analyze this simple example:

new Task(() =>
{
   int i = 0;
   do
   {
      Console.WriteLine(i);
      i++
   } while (true);
});

Technically you would expect 1, 2, 3, 4... starting to appear in console. But in practice nothing happens, because Task waits for loop to finish, which can never happen.

And here comes my question - how to run this loop asynchronously? Using Task allows not locking UI, but still results won't appear until loop is over.

You can write your code like this (inside the main methode):

await Task.Run(() => 
 int i = 0;
 do
 {
  Console.WriteLine(i);
  i++
 } while (true););

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM