[英]c# application, Handles in task manager increase and system hanged
In our application we used Threads and Delegate to get the best performance. 在我们的应用程序中,我们使用Threads和Delegate来获得最佳性能。 In order to gate our operations we use the System.Timers.Timer
class. 为了操作我们的操作,我们使用System.Timers.Timer
类。 When the application start , after 1 hour the task manager shows that the number of handles increased and cpu usage increases as well. 当应用程序启动时,1小时后,任务管理器显示句柄数量增加,cpu使用量也增加。
What can we do to dispose objects of Thread and delegate? 我们可以做些什么来处置Thread和委托的对象?
below code can help you to check this task. 下面的代码可以帮助您检查此任务。
public partial class Form1 : Form
{
System.Timers.Timer MainTimer;
public Form1()
{
InitializeComponent();
MainTimer = new System.Timers.Timer();
MainTimer.Elapsed+=new System.Timers.ElapsedEventHandler(MainTimer_Elapsed);
}
Thread MainThread;
private void button1_Click(object sender, EventArgs e)
{
MainTimer.Interval = 10;
MainTimer.Start();
}
void MainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MainThread = new Thread(new ThreadStart(DoStart));
MainThread.Start();
}
void DoStart()
{
PrintInfo();
}
delegate void PrintInfo_Delegate();
void PrintInfo()
{
if (textBox1.InvokeRequired)
{
Invoke(new PrintInfo_Delegate(PrintInfo));
}
else
{
textBox1.Text += "Test\r\n";
}
}
}
Apologies if I'm misparsing something, but it looks like once the button is clicked, you're then starting a new thread (in MainTimer_Elapsed) every 10 milliseconds? 抱歉,如果我误解了一些东西,但看起来一旦点击按钮,你就会每10毫秒开始一个新线程(在MainTimer_Elapsed中)? Without knowing more about the context / versions, it's hard to give specific advice on an alternative (async/await, TPL, etc), but off-hand it seems like anything creating new threads (especially non-background threads) like that is doing so unnessarily? 在不了解更多有关上下文/版本的情况下,很难就替代方案(async / await,TPL等)提供具体的建议,但是现在看起来就像创建新线程(尤其是非后台线程)一样如此恍惚?
For processing non-UI work, perhaps use ThreadPool.QueueUserWorkItem instead of creating your own? 对于处理非UI工作,也许使用ThreadPool.QueueUserWorkItem而不是创建自己的? For UI work, maybe use BackgroundWorker? 对于UI工作,可能使用BackgroundWorker? If you're exhausting the thread pool, you could also consider setting things like max thread count, but using TPL and avoiding the use/creation/management of threads would be better/simpler IMHO if you're able to target .Net 4.x 如果你正在耗费线程池,你也可以考虑设置最大线程数,但是如果你能够以.Net 4为目标,那么使用TPL并避免使用/创建/管理线程会更好/更简单。 X
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.