如果我在Console.Out 中看到一些关键词,我想退出程序。这是因为我们使用了一个第三方 DLL,它有一个问题,当它遇到一些特定的异常时它永远不会退出。
对我们来说唯一的解决方案似乎是监视填充回 console.Out 的日志。并且基于 console.out 上的日志,宿主应用程序可以决定遇到此类异常时要做什么。
有人告诉我可以使用跟踪监听器...但我不确定。 大家怎么看?
请您参考如下方法:
Console 类提供了 SetOut可用于将输出写入自定义流的方法。例如,您可以流式传输到 StringBuilder 并监视更改,或者编写一个自定义流实现来监视关键字。
例如,这里有一个 KeywordWatcherStreamWrapper 类,它监视指定的关键字,并在看到关键字时为所有监听器引发一个事件:
public class KeywordWatcherStreamWrapper : TextWriter
{
private TextWriter underlyingStream;
private string keyword;
public event EventHandler KeywordFound;
public KeywordWatcherStreamWrapper(TextWriter underlyingStream, string keyword)
{
this.underlyingStream = underlyingStream;
this.keyword = keyword;
}
public override Encoding Encoding
{
get { return this.underlyingStream.Encoding; }
}
public override void Write(string s)
{
this.underlyingStream.Write(s);
if (s.Contains(keyword))
if (KeywordFound != null)
KeywordFound(this, EventArgs.Empty);
}
public override void WriteLine(string s)
{
this.underlyingStream.WriteLine(s);
if (s.Contains(keyword))
if (KeywordFound != null)
KeywordFound(this, EventArgs.Empty);
}
}
示例用法:
var kw = new KeywordWatcherStreamWrapper(Console.Out, "Hello");
kw.KeywordFound += (s, e) => { throw new Exception("Keyword found!"); };
try {
Console.SetOut(kw);
Console.WriteLine("Testing");
Console.WriteLine("Hel");
Console.WriteLine("lo");
Console.WriteLine("Hello");
Console.WriteLine("Final");
} catch (Exception ex) { Console.Write(ex.Message); }
在包含整个关键字的第二个Write 语句中,将引发事件并因此抛出异常。另请注意,这会静默包装底层流并仍然写入它,因此控制台输出仍会正常生成。
示例输出:
Testing
Hel
lo
Hello
Keyword found!
