简体   繁体   English

C#如何不停地运行多个任务

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

I have a server which listens to clients in a while(true) loop.我有一个服务器,它在 while(true) 循环中监听客户端。 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.我想每 10 分钟检查一次是否有一些客户端在过去一小时内没有联系服务器并打印其名称。 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.但是我不确定如何每 10 分钟而不是每毫秒进行一次检查,无论我的想法好不好。 So What is the best way to do this?那么最好的方法是什么? Moreover, both the function and the while(true) touches the list of the clients.此外,函数和 while(true) 都涉及客户端列表。 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.这最好通过使用 Timer 函数来完成,基本上你创建它,向它传递一个函数以在经过的每个时间量调用,并设置等待时间(以毫秒为单位)。 So for your example of 10 minutes, something like this:因此,对于您的 10 分钟示例,如下所示:

// 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?由于您使用的Task.Run在您提供的样本代码,为什么不使用Task.Delay ,而你在吗?

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.如果您只是为了简单起见,则无需注册计时器及其事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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