如果有人感兴趣,这是一个扩展StringWriter()
类以在每次调用后触发事件的类writer.Flush()
。
我还添加了在每次写入后自动调用的可能性Flush()
,因为在我的情况下,确实写入控制台的第三方组件没有进行刷新。
示例用法:
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();
}
}