简体   繁体   中英

C# how to run multiple tasks in a never-stop while

I have a server which listens to clients in a while(true) loop. I keep every client's hostname in a list and save the time the client contact the server. I would like to check every 10 minutes if some of the clients didn't contact the server in the last hour and to print its name. I thought about doing something like this:

Task.Run(CheckTheClients()) //Check the passed-time of each client in the list
while(true)
{
//listen to clients, add them to list, etc.
}

But I'm not sure how to do the check every 10 minutes and not every millisecond, neither if my idea is good or not. So What is the best way to do this? Moreover, both the function and the while(true) touches the list of the clients. Is that going to make some problems?

This would be best done by using the Timer function, basically you create it, pass it a function to call at each amount of time passed, and set the time to wait in Milliseconds. So for your example of 10 minutes, something like this:

// insert this into a long running function, and scope the timer variable correctly 
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
myTimer.Interval = 600000;
myTimer.Enabled = true;


 // Define what you want to happen when the Elapsed event occurs (happens on the interval you set).
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     //do some work here
 }

You can put your thread to sleep, like this:

while (true)
{
   try
   {
        // do something
   }
   catch (Exception ex)
   {
        // save log 
   }

   Thread.Sleep(TimeSpan.FromMilliseconds(TimeSpan.FromMinutes(10).TotalMilliseconds));
}

Since you're using Task.Run in the sample code you provided, why not use Task.Delay while you're at it?

Action CheckTheClients = () => Console.WriteLine("Checking clients...");
while (true)
{
    var task = Task.Delay(1000).ContinueWith(x => CheckTheClients());
    await task;
}

No need to sign up for timer and its events, if you're going for simplicity.

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