[英]Thread.Sleep() doesn't work in application Console C#
class Program
{
static void Main(string[] args)
{
const string PATH = @"C:\My_PATH\";
const string FILE_NAME = "data_acquistion2";
const string DATETIME_STOP_RECORD = "01-04-15 17:18";
bool fichierNonExistant = false;
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;`
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
string actualPeriod = "";
if (!File.Exists(PATH + FILE_NAME + ".csv"))
{
FileStream myFs = File.Create(PATH + FILE_NAME + ".csv");
fichierNonExistant = true;
myFs.Close();
}
StreamWriter myWriter = new StreamWriter(PATH + FILE_NAME + ".csv", true);
if (fichierNonExistant == true)
{
myWriter.WriteLine("CPU Used (%)" + "," + "RAM Free (%)" + "," + "Hour and record Date");
}
while (actualPeriod != DATETIME_STOP_RECORD)
{
actualPeriod = DateTime.Now.ToString("dd/MM/yy HH:mm:ss");
// Console.WriteLine(periodeActuelle);
myWriter.WriteLine(cpuCounter.NextValue() + "," + ramCounter.NextValue() + "," + actualPeriod);
Thread.Sleep(20000); //If I add this the program doesn't write in the csv file
}
}
}`
嗨,
我在C#中的Thread.Sleep遇到问题,我开发了一个代码,用于将%CPU(已使用)和RAM直接写入csv文件。
它的工作没有延迟,但是我想每20秒写入一次此值,这就是为什么我需要使用Thread.Sleep(20000)的原因。 我也尝试了Task.Delay和我有同样的问题。
问题不在于Thread.Sleep()。 您正在使用StreamWriter,并且由于您的程序可能永远都不会关闭,因此您需要在编写后刷新StreamWriter。
加
Thread.Sleep()之前的myWriter.Flush()
问题是如果我添加Thread.Sleep()程序在csv文件中写入任何内容。
(我假设那里缺少一个“不”)
这听起来像是个冲洗问题; 您所做的更改仍保留在编写器中。 您可以尝试使用myWriter.Flush();
,但请注意,共享文件访问等仍可能会出现问题。由于您将暂停20秒(到计算机的时间很长),因此最好在不使用文件时保持文件关闭它。 完全摆脱File.AppendText(path, newLine)
,并根据需要简单地使用File.AppendText(path, newLine)
会更有效,注意在字符串中包括您选择的行尾。 然后,该文件将几乎始终关闭。
另外:您的循环退出条件需要注意; 现在,它永远不会退出自己的选择(因为actualPeriod
包含秒,而DATETIME_STOP_RECORD
不包含秒)。 最好也使用DateTime
和<
(您可以从时间之前到时间之后再不精确地匹配时间)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.