. Net – is there a textwriter subclass that triggers an event when writing text?
I wrote a method that accepts textwriter as a parameter (usually console. Out, but not necessarily)
When I call this method, I write some progress information to textwriter However, since this method may run for a long time, I want to update my UI with some status information
At present, I use stringwriter, but it has no events So the first time I get results from stringwriter is after the method is completed
Now I'm searching for a class that inherits from textwriter and triggers textchanged event or similar I know this shouldn't be hard to achieve, but I bet the CLR team has done it for me and I can't find a suitable course
Solution
If anyone is interested, this is a class that extends the stringwriter () class, every time the writer is called Event triggered after flush()
I also added posibility to automatically call flush () after each write, because in my case, the third-party component, written to the console, does not perform refresh
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 in time without waiting for the method to complete
void writer_Flushed(object sender,EventArgs args)
{
UpdateUi(sender.ToString());
}
This 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();
}
}
