[英]C# how to run multiple tasks in a never-stop while
我有一個服務器,它在 while(true) 循環中監聽客戶端。 我將每個客戶端的主機名保存在一個列表中,並節省了客戶端聯系服務器的時間。 我想每 10 分鍾檢查一次是否有一些客戶端在過去一小時內沒有聯系服務器並打印其名稱。 我想過做這樣的事情:
Task.Run(CheckTheClients()) //Check the passed-time of each client in the list
while(true)
{
//listen to clients, add them to list, etc.
}
但是我不確定如何每 10 分鍾而不是每毫秒進行一次檢查,無論我的想法好不好。 那么最好的方法是什么? 此外,函數和 while(true) 都涉及客戶端列表。 這樣會不會出問題?
這最好通過使用 Timer 函數來完成,基本上你創建它,向它傳遞一個函數以在經過的每個時間量調用,並設置等待時間(以毫秒為單位)。 因此,對於您的 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
}
你可以讓你的線程進入睡眠狀態,如下所示:
while (true)
{
try
{
// do something
}
catch (Exception ex)
{
// save log
}
Thread.Sleep(TimeSpan.FromMilliseconds(TimeSpan.FromMinutes(10).TotalMilliseconds));
}
由於您使用的Task.Run
在您提供的樣本代碼,為什么不使用Task.Delay
,而你在嗎?
Action CheckTheClients = () => Console.WriteLine("Checking clients...");
while (true)
{
var task = Task.Delay(1000).ContinueWith(x => CheckTheClients());
await task;
}
如果您只是為了簡單起見,則無需注冊計時器及其事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.