Reputation:
I have a logger that has to write information several times per second:
long iii = 0;
while (true)
Logger.WriteLog("=====> " + iii++);
the logger basically just writes on file
public static bool WriteLog(string newLines)
{
string txtLines = string.Empty;
strError = string.Empty;
...
lock (thisLock)
{
string strDateTime = "[" + DateTime.Now.ToString() + "." + DateTime.Now.ToString("fff") + strDelta + "] ";
newLines = strDateTime + newLines;
newLines = newLines.Replace(Environment.NewLine, Environment.NewLine + strDateTime);
lastLogTime = DateTime.Now;
...
File.AppendAllText(_fileName, newLines);
return true;
}
}
}
so what I'd expect would be a increasing list of contiguouos numbers like 1,2,3,4,5,etc.
instead what I get is:
[27/03/2017 11:09:25.540 - START ] =====> 0
[27/03/2017 11:09:25.541 - 00:00:00.001] =====> 1
[27/03/2017 11:09:25.542 - 00:00:00.001] =====> 2
[27/03/2017 11:09:25.556 - 00:00:00.014] =====> 4
[27/03/2017 11:09:25.557 - 00:00:00.001] =====> 5
[27/03/2017 11:09:25.582 - 00:00:00.025] =====> 7
[27/03/2017 11:09:25.592 - 00:00:00.010] =====> 9
So it's clear that I'm doing something wrong. From here I get that append text should do all by itself: write, flush, close.
That said I have something else strange going on. If I launch the example in debug mode and minimize it, I get the following error with the debugger showing that following picture:
Managed Debugging Assistant 'ContextSwitchDeadlock' has detected a problem in 'C:\Temp\WpfApplication1\WpfApplication1\bin\Debug\WpfApplication1.vshost.exe'.
Additional information: The CLR has been unable to transition from COM context 0x4236c0 to COM context 0x423830 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.
thanks for helping.
Upvotes: 0
Views: 445
Reputation: 161
I've been having a similar problem when debugging a BackGroundWorker thread containing a for/next loop writing out debug data - data cut off in the middle of a line and the following lines missing at the end of the file. Closing File.AppendText after the loop fixed it.
Upvotes: 0
Reputation: 2583
OK I had a similar issue and solved by putting a very small pause after the AppendText. Whatever will do even System.Threading.Sleep(1); As for the other problem, as Mrinal Kamboj said you might try to remove the lock.
Upvotes: 0