[英]Suppress 3rd party library console output?
I need to call a 3rd party library that happens to spew a bunch of stuff to the console. 我需要调用一个第三方库来碰巧向控制台吐出一堆东西。 The code simply like this...
代码就像这样......
int MyMethod(int a)
{
int b = ThirdPartyLibrary.Transform(a); // spews unwanted console output
return b;
}
Is there an easy way to suppress the unwanted console output from ThirdPartyLibrary? 有没有一种简单的方法来抑制ThirdPartyLibrary中不需要的控制台输出? For performance reasons, new processes or threads cannot be used in the solution.
出于性能原因,解决方案中不能使用新进程或线程。
Well you can use Console.SetOut
to an implementation of TextWriter
which doesn't write anywhere: 那么你可以使用
Console.SetOut
来实现TextWriter
,它不会在任何地方写入:
Console.SetOut(TextWriter.Null);
That will suppress all console output though. 这将抑制所有控制台输出。 You could always maintain a reference to the original
Console.Out
writer and use that for your own output. 您可以始终保持对原始
Console.Out
的引用,并将其用于您自己的输出。
Here's one way to do it (which also usually covers managed C++ applications that you P/Invoke from C# or otherwise): 这是一种方法(通常还包括您从C#或其他方式调用的托管C ++应用程序):
internal class OutputSink : IDisposable
{
[DllImport("kernel32.dll")]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
public static extern int SetStdHandle(int nStdHandle, IntPtr hHandle);
private readonly TextWriter _oldOut;
private readonly TextWriter _oldError;
private readonly IntPtr _oldOutHandle;
private readonly IntPtr _oldErrorHandle;
public OutputSink()
{
_oldOutHandle = GetStdHandle(-11);
_oldErrorHandle = GetStdHandle(-12);
_oldOut = Console.Out;
_oldError = Console.Error;
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
SetStdHandle(-11, IntPtr.Zero);
SetStdHandle(-12, IntPtr.Zero);
}
public void Dispose()
{
SetStdHandle(-11, _oldOutHandle);
SetStdHandle(-12, _oldErrorHandle);
Console.SetOut(_oldOut);
Console.SetError(_oldError);
}
}
This class can be called as follows: 可以按如下方式调用此类:
using (new OutputSink())
{
/* Call 3rd party library here... */
}
This will have an impact. 这会产生影响。 Any application logic that tries to use the console from another thread during the time you are
using
the OutputSink
will not function correctly to write to the standard output, standard error, console output, or console error. 在您
using
OutputSink
期间尝试从另一个线程使用控制台的任何应用程序逻辑都无法正确写入标准输出,标准错误,控制台输出或控制台错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.