我有一个关于内存使用和多线程应用程序的技术问题。
我的场景是我构建了一个服务器应用程序(在 C# 中),它不断运行并定期(每分钟)更新数据库信息。应用程序分为两个线程。第一个线程处理 UI。第二个线程在一个连续循环中处理所有繁重的工作(直到 Tasks flag = false)。当第二个线程完成其任务时,它会进入睡眠状态 60 秒,然后循环并再次执行此操作。
该应用程序运行愉快,没有内存问题或资源问题,但我注意到一些我不明白的奇怪现象。
当应用程序正在工作(执行其任务)时,它会使用 100% 的可用 CPU,并且内存下降到 80k kb。但是当任务完成并且第二个线程进入睡眠状态时,内存会增加到 180k kb。
如果有人能解释一下,我将不胜感激?
代码
private void BackgroundWorker1()
{
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(
delegate(object o, DoWorkEventArgs args)
{
BackgroundWorker b = o as BackgroundWorker;
{
while (Tasks)
{
try
{
SetValue(System.DateTime.Now.ToString() + " - Opening DB Connection \r\n");
GlobalVars.WiFiToolDataSource.Open();
SetValue(System.DateTime.Now.ToString() + " - Starting Task \r\n");
TicketFunctions.GetBOSSTickets();
SetValue(System.DateTime.Now.ToString() + " - Got Tickets from BOSS \r\n");
EmailFunctions.GetEmails("");
SetValue(System.DateTime.Now.ToString() + " - Got Emails from Inbox \r\n");
EmailFunctions.GetEmails("WiFI Survey Archive");
SetValue(System.DateTime.Now.ToString() + " - Got Emails from Archive \r\n");
EmailFunctions.checkEmails("BodyText", GlobalVars.ApplicationData + "Emails");
SetValue(System.DateTime.Now.ToString() + " - Loaded Emails in DB \r\n");
EmailFunctions.CreateEmailIndexes();
SetValue(System.DateTime.Now.ToString() + " - Created Email Indexes \r\n");
TicketFunctions.UpdateTicketList();
SetValue(System.DateTime.Now.ToString() + " - Updated Tickets \r\n");
TicketFunctions.BuildTicketKB();
SetValue(System.DateTime.Now.ToString() + " - Finished Build Knowledge Base \r\n");
SetValue(System.DateTime.Now.ToString() + " - Finished Refresh \r\n");
if (!Tasks)
break;
if (System.DateTime.Now.Hour.ToString("HH") == "00")
{
if (newFile)
{
string CDate = System.DateTime.Now.AddDays(-1).ToString("ddMMyyyy");
string FileName = "QA_LOG_" + CDate + ".txt";
System.IO.File.WriteAllText(GlobalVars.ApplicationData + @"QA Server Log\" + FileName, textBox1.Text);
ClearValue();
newFile = false;
}
}
if (System.DateTime.Now.Hour.ToString("HH") == "01")
{
newFile = true;
}
Thread.Sleep(60000);
}
catch (Exception e)
{
SetValue("Error : " + e.ToString() + " \r\n"); ;
}
finally
{
GlobalVars.WiFiToolDataSource.Close();
}
}
}
});
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate(object o, RunWorkerCompletedEventArgs args)
{
SetValue(System.DateTime.Now.ToString() + " - Complete \r\n");
});
bw.RunWorkerAsync();
}