MigDinny
MigDinny

Reputation: 119

Async Infinite Loop

I'm programming a C# software and it has some functions which make like a check-in on my server 5 in 5 seconds (they send http request, but it doesn't matter for my problem). Here is the code:

    log();

    while (true)
    {

        alive(); // this sends an http request to my server
        Thread.Sleep(5000); // sleep for 5 seconds avoiding computer overcharge
    }

    MessageBox.Show("after infinite loop"); // this is never executed but i pretend to do so

So, my problem is: I got an infinite loop and after that infinite loop I want to write ANOTHER infinite loop which runs asynchronously and does something each 100ms. Of course "that something" i cannot write it inside the existing loop because that loop is executed 5 in 5 seconds. I got to code a lot of infinite loops like those, each one being executed independently from another (or asynchronously) with different times.

I have searched a lot and my conclusion is to write every loop asynchronously. My question is: how to do that? Every code I found was completely incomprehensible for me. I simply couldn't understand them. So, if you have a better option than async infinite loops (which i think is the best option indeed), you can speak about it, otherwise i need some help coding this async infinite loops...

Sorry for my bad english, thanks in advance

Upvotes: 7

Views: 24610

Answers (4)

Maahi
Maahi

Reputation: 326

You can do it using async await as follows:

Create an async calling method that will call your multiple methods having infinite loop in non blocking way.

private async void Method1()
{

DoSomeInfiniteWork1(); //Don't use await here

MessageBox.Show("after First infinite loop"); //now it will executed instantly after calling DoSomeInfiniteWork1 method having infinite while loop.

DoSomeInfiniteWork2();

...some other task
}

Create first method async having infinite loop as follows:

static bool cancelwork1=false;
private async Task DoSomeInfiniteWork1()
{
log();
    while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork1)
        break;

        alive(); // this sends an http request to my server
        Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }
}

Create second method having another infinite loop:

static bool cancelwork2=false;
private async Task DoSomeInfiniteWork2()
{

while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork2)
        break;

       DoSomeOtherWork();// Do your other work 
       Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }

}

Thanks !!

Upvotes: 2

John Clifford
John Clifford

Reputation: 847

Follow these steps:

  • Put your loops inside their own methods
  • use Task.Factory.StartNew(() => {methodname}());
  • use Task.Factory.StartNew(() => {methodname}()); to call them.

You need to use System.Threading.Tasks for this, which may have been added by default when you created the project, but if not, you'll need to add it.

Upvotes: 1

usr
usr

Reputation: 171178

var loop1Task = Task.Run(async () => {
 while (true) {
  await Task.Delay(5000);
 }
});

var loop2Task = Task.Run(async () => {
 while (true) {
  await Task.Delay(100);
 }
});

Now you have two loops. You can add code to them.

Upvotes: 23

David
David

Reputation: 218798

and after that infinite loop...

That's not really what "infinite" means :)

You can have two simultaneous running processes, simply put them in their own threads. This would also have the added benefit that your application host isn't blocked by your loop, so you'd be free to do other things with the application host. (And it doesn't appear to be "frozen" to the host system.)

It could be something as simple as this...

public class Worker
{
    public void DoWork()
    {
        while (true)
        {
            alive(); // this sends an http request to my server
            Thread.Sleep(5000); // sleep for 5 seconds avoiding computer overcharge
        }
    }
}

Then to start it as a thread:

var workerObject = new Worker();
var workerThread = new Thread(workerObject.DoWork);
workerThread.Start();

You can send a variety of information and signals to threads to provide them with data from the consuming code and to control them while they're running. (Since you certainly wouldn't want runaway threads that you can't interact with.) So this is just a very simple example to get you started and illustrate the concept.

You can find a lot more information about and more complete examples on MSDN, among a number of other places.

Upvotes: 8

Related Questions