我正在尝试使用 IPC 来允许我的应用程序仅通过启动器打开。为此,我决定使用命名管道来传递“请求”,并在更新和校验完成后打开主应用程序的登录窗口,但我对 C# 还很陌生,遇到了一些我似乎无法解决的问题找到它们的来源...
完成所有更新并且启动器创建并请求打开应用程序后,主应用程序将打开,然后立即关闭,没有任何错误消息/日志。但是,如果我尝试独立打开应用程序,那么它会打开(并保持这种方式),但仅在进程列表中,这本身就是另一个大问题......
private static async Task StarterAsync()
{
string executablePath = "Application.exe";
try
{
Process.Start(executablePath);
using NamedPipeServerStream pipeServer = new("MyAppNP", PipeDirection.Out);
await pipeServer.WaitForConnectionAsync();
byte[] messageBytes = Encoding.UTF8.GetBytes("LaunchRequest");
await pipeServer.WriteAsync(messageBytes);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
Application.Current.Shutdown();
}
}
namespace MyApp
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
string pipeName = "MyAppNP";
using NamedPipeServerStream pipeServer = new(pipeName, PipeDirection.In);
try
{
pipeServer.WaitForConnection();
byte[] buffer = new byte[256];
int bytesRead = pipeServer.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (message == "LaunchRequest")
{
Login.Login loginWindow = new();
loginWindow.Show();
}
else
{
MessageBox.Show("Launcher request mismatch. Exiting the application.");
pipeServer.Close();
Current.Shutdown();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
pipeServer.Close();
Current.Shutdown();
}
}
}
}
有更多经验的人可以帮助我找出导致所有这些问题发生的原因吗?
我试过:
我检查了一些日志,但找不到与这些问题相关的任何内容。
我还没有尝试任何调试,我只是太沮丧了,只想在接下来的 12 小时内远离任何与代码相关的事情 xD
我在期待:
启动器完成更新/检查重要文件后,它会发送打开主应用程序的请求,当它完成时,它会自行关闭。
之后主应用程序将像以前一样正常运行。
双方都在创建
NamedPipeServerStream
并等待对方连接;其中之一应该是 NamedPipeClientStream
并建立连接。
或者,您可以使用匿名管道(
ProcessStartInfo.RedirectStandardOutput
和朋友)。当您具有父/子进程关系时,这是更常见的方法。