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,我遇到了同样的问题。
答案 0 :(得分:1)
问题不在于Thread.Sleep()。你正在使用StreamWriter,因为你的程序可能永远不会关闭,你需要在写完后刷新StreamWriter。
添加
在Thread.Sleep()之前的答案 1 :(得分:0)
问题是如果我添加Thread.Sleep(),程序会在csv文件中写入任何内容。
(我假设缺少"没有'#34;在那里)
这听起来像是一个潮红的问题;您的更改仍在作者中缓冲。您可以使用myWriter.Flush();
尝试,但请注意,您可能仍会遇到共享文件访问等问题。因为您将暂停20秒(很长一段时间如果你没有使用它,你也可以保持文件关闭。完全摆脱作家 并根据需要简单地使用File.AppendText(path, newLine)
会更有效,并注意在字符串中包含你选择的行结尾。然后几乎所有时间都会关闭文件。
另外:你的循环退出条件需要注意;现在它将从不退出自己的选择(因为actualPeriod
包括秒,而DATETIME_STOP_RECORD
没有。最好同时使用DateTime
和<
(你可以在时间之前到之后的时间而不是完全按时完成)。