我是一个有用的助手,可以为您翻译文本。
我正在撰写一篇关于C# WPF程序的论文,但遇到了一个我不理解的错误。
在我的MainWindow代码中,我使用以下方式启动一个新线程:
在PasswordWindow的构造函数中它会崩溃。我尝试了STA + Dispatcher,MTA + Dispatcher,只用STA等方法,但都没有起作用...我真的不明白。
有人能解释一下为什么它仍然说线程需要是STA线程吗?
感谢任何形式的帮助!
我正在撰写一篇关于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等方法,但都没有起作用...我真的不明白。
有人能解释一下为什么它仍然说线程需要是STA线程吗?
感谢任何形式的帮助!