C# 在与无形应用程序不同的线程上创建窗体



我目前正在创建一个无形的C#应用程序,它将充当SignalR客户端。目标是让客户端在后台以静默方式运行,并在 SignalR 触发时显示窗体。

目前,我在显示 GUI 时遇到问题。由于 SignalR 需要异步运行,并且我不能使用异步Main()方法,因此我目前必须使用Task.ContinueWith

static void Main()
{
_url = "https://localhost:44300";
var hubConnection = new HubConnection(_url);
var hubProxy = hubConnection.CreateHubProxy("HubName");
hubConnection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
MessageBox.Show("There was an error opening the connection");
}
else
{
Trace.WriteLine("Connection established");
}
}).Wait();
hubProxy.On("showForm", showForm);
Application.Run();
}

这是 showForm 方法:

private static void ShowForm()
{
var alertForm = new AlertForm();
alertForm.Show();
}

起初这工作正常 - 它连接到集线器,并在我从服务器调用showForm时调用showForm()方法。但是,窗体永远不会呈现并显示为"未响应"。调用.ShowDialog将意味着窗体实际呈现,但 SignalR 客户端停止侦听中心。

那么,如何显示窗体,使其在单独的线程上运行并且不会阻止我的 SignalR 客户端的执行?

你的代码问题是;虽然你在Main中使用Application.Run创建了一个消息循环,但hubProxy.On在不同的线程上执行。 最简单的解决方案是在其自己的线程中运行AlertForm的每个实例,并具有自己的消息循环。

private static void ShowForm()
{
var t = new Thread(() =>
{
var alertForm = new AlertForm();
alertForm.Show();
Application.Run(alertForm); //Begins running a standard application message loop on the current thread, and makes the specified form visible.
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}

最新更新