If anyone is interested, this is a class that extends the StringWriter()
class to fire events after every call to writer.Flush()
.
I also added the posibillity to automatically call Flush()
after every write, since, in my case, a third party component, that did write to the console, didn't do a flush.
Sample usage:
void DoIt()
{
var writer = new StringWriterExt(true); // true = AutoFlush
writer.Flushed += new StringWriterExt.FlushedEventHandler(writer_Flushed);
TextWriter stdout = Console.Out;
try
{
Console.SetOut(writer);
CallLongRunningMethodThatDumpsInfoOnConsole();
}
finally
{
Console.SetOut(stdout);
}
}
Now I can display some status information just in time and don't need to wait for the method to finish.
void writer_Flushed(object sender, EventArgs args)
{
UpdateUi(sender.ToString());
}
And here is the class:
public class StringWriterExt : StringWriter
{
[EditorBrowsable(EditorBrowsableState.Never)]
public delegate void FlushedEventHandler(object sender, EventArgs args);
public event FlushedEventHandler Flushed;
public virtual bool AutoFlush { get; set; }
public StringWriterExt()
: base() { }
public StringWriterExt(bool autoFlush)
: base() { this.AutoFlush = autoFlush; }
protected void OnFlush()
{
var eh = Flushed;
if (eh != null)
eh(this, EventArgs.Empty);
}
public override void Flush()
{
base.Flush();
OnFlush();
}
public override void Write(char value)
{
base.Write(value);
if (AutoFlush) Flush();
}
public override void Write(string value)
{
base.Write(value);
if (AutoFlush) Flush();
}
public override void Write(char[] buffer, int index, int count)
{
base.Write(buffer, index, count);
if (AutoFlush) Flush();
}
}