Is there a child class TextWriter that fires an event if the text is written?

I wrote a method that takes TextWriteras an argument (usually Console.Out, but not necessary).

When I call this method, some progress data is written to TextWriter. However, since this method may work for a long time, I want to update my interface with some status information.

I am currently using StringWriter, but it has no events. So the first time I get the result from StringWriter, after the method finishes.

Now I am looking for a class that inherits from TextWriterand fires the TextChanged event or something like that. I know that this should not be difficult to implement, but I am sure that the CLR team has already done this for me, I just can not find a suitable class.

+3
source share
2 answers

If anyone is interested, this is a class that extends the class StringWriter()to fire events after each call writer.Flush().

I also added the ability to automatically call Flush()after each recording, since in my case the third-party component that was recording to the console did not make a flash.

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);
    }
}

.

void writer_Flushed(object sender, EventArgs args)
{
    UpdateUi(sender.ToString());
}

:

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();
    }
}
+9

BCL , , , .

.

+3

Source: https://habr.com/ru/post/1764669/


All Articles