Reputation: 47
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
}
}
}`
Hi,
I have a problem with Thread.Sleep in C#, I developped a code for writting the % CPU (used) and the RAM directly into a csv file.
It works without a delaying, but I want to write this values every 20s, that's why I need to use Thread.Sleep(20000). I have also tried Task.Delay and I have the same problem.
Upvotes: 1
Views: 877
Reputation: 1064114
The problem is if I add the Thread.Sleep() the program write anything in the csv file.
(I'm assuming there is a missing "doesn't" in there)
This sounds like a flushing problem; your changes are still buffered in the writer. You could try using myWriter.Flush();
, but note that you might still get problems with shared file access etc. Since you're going to be pausing for 20 seconds (a very long time to a computer), you might as well keep the file closed when you aren't using it. It would be more effective to get rid of the writer completely and simply use File.AppendText(path, newLine)
as necessary, noting to include your choice of line-ending in the string. Then the file will be closed almost all of the time.
Additionally: your loop exit condition needs attention; right now it will never exit of its own choice (since actualPeriod
includes seconds, and DATETIME_STOP_RECORD
does not). It would be better to use a DateTime
and <
, too (you could go from before the time to after the time without ever hitting exactly the time).
Upvotes: 0
Reputation: 9041
The problem isn't the Thread.Sleep( ). You're using a StreamWriter and since your program is probably never closing, you need to flush the StreamWriter after you write.
Add
myWriter.Flush( ) before the Thread.Sleep( )
Upvotes: 1