Home > Software engineering >  How to run loop async in c#
How to run loop async in c#

Time:01-04

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.

CodePudding user response:

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

await Task.Run(() => 
 int i = 0;
 do
 {
  Console.WriteLine(i);
  i  
 } while (true););
  •  Tags:  
  • Related