TStreamWriter (Auto)Flush does not?

坚强是说给别人听的谎言 提交于 2020-01-13 20:21:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!