[英]How to do multiple tasks in an infinite loop while using with thread.sleep
[英]Multiple threads with infinite loop and thread.sleep high CPU usage
在我的控制台應用程序中,我有一些線程,每個線程都有一個帶有 Thread.Sleep 的無限循環。 有很多線程,因為每個線程都獨立於其他線程。 每個循環在每個waitingTime
時間運行,我希望它永遠不會停止。
static int waitingTime= 5 * 60 * 1000;
static void Main(string[] args)
{
Thread thread1 = new Thread(() => Thread1());
Thread thread2 = new Thread(() => Thread2());
Thread thread3 = new Thread(() => Thread3());
...
thread1.Start();
thread2.Start();
thread3.Start();
...
}
static void Thread1()
{
do
{
// Connect to DB and do something...
try
{
using (SqlConnection connection = MyDBClass.MyDBConnection())
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT x, y FROM Table WITH (NOLOCK);";
SqlDataReader sdr = command.ExecuteReader();
while (sdr.Read())
{
MyObject obj = new MyObject(sdr[0] as string, ...);
MyStaticClass.SetMyObject(obj); // Open a new DB connection on different server and do an Update.
}
sdr.Close();
sdr.Dispose();
}
}
catch
{
}
Thread.Sleep(waitingTime);
}
while (true);
}
static void Thread2()
{
do
{
// Connect to DB and do something...
Thread.Sleep(waitingTime);
}
while (true);
}
...
我已經讀過在這種情況下使用 Thread.Sleep() 並不好,並且應該使用EventWaitHandle之類的解決方案。 這種情況的最佳解決方案是什么以及如何實施。
使用Thread.Sleep()
休眠的線程消耗的 CPU 資源為零,因此嘗試使用EventWaitHandle
原語或其他方式對此進行改進是沒有意義的。 你不能打敗零。 您可以改進的是線程消耗的 RAM,它們的堆棧為1 MB ,加上它們在堆上分配的 memory(這取決於它們在工作時所做的事情)。 因此,通過使用單個線程而不是三個線程,您可以將 RAM 消耗減少 2 MB 或更多,這對於在現代 PC 上運行的控制台應用程序來說幾乎沒有什么意義。 所以我不會在你的地方擔心它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.