gpt4 book ai didi

c# - 具有无限循环和 thread.sleep 高 CPU 使用率的多线程

转载 作者:行者123 更新时间:2023-12-05 06:16:31 25 4
gpt4 key购买 nike

在我的控制台应用程序中,我有一些线程,每个线程都有一个带有 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对于他们的堆栈,加上他们在堆上分配的内存(这取决于他们在工作时所做的事情)。因此,通过使用单个线程而不是三个线程,您可以将 RAM 消耗减少 2 MB 或更多,这对于在现代 PC 上运行的控制台应用程序来说几乎不算什么。所以我不会为你担心。

关于c# - 具有无限循环和 thread.sleep 高 CPU 使用率的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62083067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com