问题
Despite what is said in Text File Writing performances in Delphi (comments under Ken White's answer), I see the TStreamWriter not flushing with the following code:
procedure TFrmAddEvents.LogEvent(AEvent: TcxSchedulerEvent);
begin
if not Assigned(FStreamWriter) then
begin
FStreamWriter := TStreamWriter.Create(TFileStream.Create(ChangeFileExt(ParamStr(0),'.log'),fmCreate or fmOpenRead));
FStreamWriter.AutoFlush := true;
end;
FStreamWriter.WriteLine(TcxEventDescription(AEvent));
// Even this has no effect:
FStreamWriter.Flush;
end;
Even after executing the
if Assigned(FStreamWriter) then FStreamWriter.Free;
in FormClose, the file is still 0 bytes.
When the program has finished executing, the file is 600+ kB.
- FStreamWriter is a form property of type TStreamWriter.
- Creating with
fmCreate or fmOpenWrite
makes no difference. - TcxEventDescription does give a valid return string > 500 bytes containing CRLFs.
- As you can see I don't do anything with Encoding, all default Unicode stuff.
- I'm running from the Delphi XE2 IDE or as a standalone executable.
- 32 bit app under Win7 64bit
What can be going on and how to fix?
[Edited 7. Jan 2014]
Updated code after Uwe's answer; still does not work:
procedure TFrmAddEvents.LogEvent(AEvent: TcxSchedulerEvent);
var lName: string;
begin
lName := ChangeFileExt(ParamStr(0),'.log');
if not Assigned(FStreamWriter) then
begin
FStreamWriter := TStreamWriter.Create(lName); // Or TStreamWriter.Create(lName,true);
FStreamWriter.AutoFlush := true;
end;
FStreamWriter.WriteLine(TcxEventDescription(AEvent));
// Next does not help either:
FStreamWriter.Flush;
end;
Until I call FStreamWriter.Free the file remains 0 bytes.
回答1:
The TStreamWriter flushing means it will just write its buffer to the attached stream. This does not necessary mean that any TFileStream will flush its OS buffers, just because the TStreamWriter doesn't know of any TFileStream (only TStream).
To make it worse, you are giving a TFileStream instance created by your own. So TStreamWriter doesn't take ownership of the stream and thus will not free it on Destroy. The freeing of the stream would however close the file and thus write the content to disk.
来源:https://stackoverflow.com/questions/20953302/tstreamwriter-autoflush-does-not