[英]How to close NamedPipeClientStream?
I can't close my WPF application because the NamedPipeClientStream endlessly runs.我无法关闭我的 WPF 应用程序,因为 NamedPipeClientStream 无休止地运行。 I tried using
ConnectAsync
, I tried disposing it, but no matter what it prevents the process from ending.我尝试使用
ConnectAsync
,我尝试处理它,但无论如何它都会阻止进程结束。
I use the pipe to listen for messages so it needs to run until the application quits.我使用管道来侦听消息,因此它需要运行直到应用程序退出。
This is my current attempt:这是我目前的尝试:
public MainWindow()
{
namedPipeClient = new(System.Configuration.ConfigurationManager.AppSettings["AppGUID"]!);
Thread PipeThread = new(() =>
{
while (true)
{
try
{
PipeReceive();
}
catch (TimeoutException) { }
catch (ObjectDisposedException) { break; }
}
});
PipeThread.Start();
}
// Called when window is closed
protected override void OnClosed(EventArgs e)
{
namedPipeClient.Close();
namedPipeClient.Dispose();
base.OnClosed(e);
}
private void PipeReceive()
{
namedPipeClient.Connect(1000);
if (namedPipeClient.IsConnected)
{
// Retrieve message
}
}
The issue didn't have anything to do with named pipes.这个问题与命名管道没有任何关系。 I was under the impression it did because in Visual Studio's "Running Tasks" it showed a reference to the named pipe methods and listed them as active.
我有这样的印象,因为在 Visual Studio 的“运行任务”中,它显示了对命名管道方法的引用并将它们列为活动的。
The real issue was the I had changed the application ShutdownMode
to OnExplicitShutdown
so even after the main window was closed the application would remain running unless the Shutdown()
method is called.真正的问题是我已将应用程序
ShutdownMode
更改为OnExplicitShutdown
,因此即使在主窗口关闭后,应用程序仍将保持运行,除非调用Shutdown()
方法。 My fix was to override the OnClosed
event.我的解决方法是覆盖
OnClosed
事件。
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
System.Windows.Application.Current.Shutdown();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.