Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading