我正在写关于 C# WPF 程序的论文,但我遇到了一个我不明白的错误。
在我的 MainWindow 代码中的某处,我开始了一个新线程,如下所示:
Thread searchServer = new Thread(new ThreadStart(doSearchServer));
searchServer.SetApartmentState(ApartmentState.STA);
searchServer.Start();
doSearchServer 方法执行以下操作:
private void doSearchServer()
{
bool connected = ServerConnection.authentication();
ServerConnection.getDeviceList();
gotDataFromServer = connected;
if (connected)
..
..
}
ServerConnection 类是静态的,因为我在其他一些 Windows 中也需要该类。
在 ServerConnection.authentication() 中,客户端(我的程序)尝试在我的服务器上进行身份验证。如果需要密码,我想打开一个新的 PasswordWindow,如您所见:
public static bool authentication()
{
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 55042);
IPEndPoint ipRec = new IPEndPoint(IPAddress.Any, 0);
byte[] bytes = Encoding.UTF8.GetBytes("authent|Username|Windows");
client.Send(bytes, bytes.Length, ip);
//Receive Answer
byte[] recBuffer = client.Receive(ref ipRec);
string recString = Encoding.UTF8.GetString(recBuffer);
if (recString.Equals("authent|password"))
{
//Send Passwort
Console.WriteLine("Password Required");
Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
{
PasswordWindow pw = new PasswordWindow();
pw.ShowDialog();
if (pw.ShowDialog() == true)
{
//send PW
}
else
{
//Dont send PW
}
}));
client.Send(bytes, bytes.Length, ip);
.
.
.
}
在 PasswordWindow 构造函数中它崩溃了。我尝试了 STA + Dispatcher、MTA + Dispatcher、STA only..我试过的任何东西都不起作用......我真的不明白。
谁能解释一下为什么它仍然说线程需要是 STA 线程?
感谢您的帮助!!
最佳答案
更改 Dispatcher.CurrentDispatcher
到
System.Windows.Application.Current.Dispatcher
因为当从不是“UI 线程”的线程访问 Dispatcher.CurrentDispatcher
属性时(与第一个启动应用程序的 Dispatcher
关联的线程) place),一个新的 Dispatcher
被创建,这不是你在这里需要的。
关于c# - 线程必须是 STA-Thread,但它已经是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629298/