这就是我最终用来避免这个问题的方法。这是此 MSDN 论坛主题中显示的解决方案的一个非常简化的版本:
https://social.msdn.microsoft.com/Forums/en-US/7bbf5a0b-3c22-4836-b271-999e514c321b/namedpipeclientstreamconnect-causes-cpu-hang-is-there-a-workaround
[return: MarshalAs( UnmanagedType.Bool )]
[DllImport( "kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true )]
private static extern bool WaitNamedPipe( string name, int timeout );
/// <summary>
/// Method to test if Windows considers that a named pipe of a certain name exists or not.
/// </summary>
internal static bool DoesNamedPipeExist(string pipeFileName)
{
try
{
return WaitNamedPipe(@"\\.\pipe\" + pipeFileName, 0);
}
catch (Exception)
{
return false;
}
}
这是使用 NamedPipeClientStream.Connect() 方法的地方的代码:
// If necessary, wait for the server end to open the named pipe. Otherwise the following
// NamedPipeClientStream.Connect() method can burn up 100% CPU time while waiting for
// the connection.
while (true)
{
if (DoesNamedPipeExist(_pipeFileName))
break;
Thread.Sleep(1000);
}
// Connect to named pipe server - this is a blocking call, and in fact is a blocking
// call that can use 100% CPU time while waiting for a connection
_namedPipeClient.Connect();