WPF应用使用NamedPipe发送命令后抛出System.ObjectDisposedException问题求助
WPF命名管道接收命令后抛出ObjectDisposedException错误
问题场景
在WPF应用中通过命名管道接收外部命令,消息能正常接收并弹出显示,但关闭消息框后会抛出System.ObjectDisposedException: 'Cannot access a closed pipe.'错误。
原实现代码:
public MainWindow() { InitializeComponent(); _pipeServer = new NamedPipeServerStream("CommandPipe", PipeDirection.In); Thread listenThread = new Thread(ListenForCommands); listenThread.Start(); } private void ListenForCommands() { while (true) { if (!_pipeServer.IsConnected) { _pipeServer.WaitForConnection(); } using (StreamReader sr = new StreamReader(_pipeServer)) { while (_pipeServer.IsConnected) { string commandLineArguments = sr.ReadLine(); if (string.IsNullOrEmpty(commandLineArguments)) continue; // Process the command line arguments ProcessCommand(commandLineArguments); } } } } private void ProcessCommand(string commandLineArguments) { // Your command processing logic here MessageBox.Show(commandLineArguments); //... }
报错信息
System.ObjectDisposedException: 'Cannot access a closed pipe.'
测试方式
通过命令提示符发送命令:
echo Hello World > .\pipe\CommandPipe
解决方案
修正后的可行代码:
public MainWindow() { InitializeComponent(); _pipeWorker = new BackgroundWorker(); _pipeWorker.DoWork += PipeWorker_DoWork; _pipeWorker.RunWorkerAsync(); } private void PipeWorker_DoWork(object sender, DoWorkEventArgs e) { _pipeServer = new NamedPipeServerStream("CommandPipe", PipeDirection.In); while (true) { _pipeServer.WaitForConnection(); using (var reader = new StreamReader(_pipeServer)) { string command = reader.ReadLine(); // Handle the command here Dispatcher.Invoke(() => HandleCommand(command)); } } } private void HandleCommand(string command) { _pipeServer.Dispose(); _pipeServer = new NamedPipeServerStream("CommandPipe", PipeDirection.In); // do anything you want with the command received command = command.TrimEnd(); switch (command) { case "quit": // Do something System.Windows.Application.Current.Shutdown(); break; case "minimize": // Do something else this.WindowState = WindowState.Minimized; break; default: // Handle unknown command break; } }
测试命令示例
echo quit > \\.\pipe\CommandPipe echo minimize > \\.\pipe\CommandPipe
内容的提问来源于stack exchange,提问作者MrBi
相关产品推荐
相关产品推荐

