我已经在 stackoverflow 和网络上进行了搜索,但找不到解决问题的方法。
我以异步方式从流中读取。我想要回调来更新 gui
[STAThread]
private void ClientLoggedCallback(IAsyncResult res)
{
try
{
MailClient.Helpers.Client.getInstance().client.GetStream().EndWrite(res);
MailClient.Helpers.Client.getInstance().asyncRecieveEncryptedProtocolMessage(new AsyncCallback(LoginInfo_recieved));
}
catch { }
}
[STAThread]
private void LoginInfo_recieved(IAsyncResult res)
{
try
{
MailClient.Helpers.Client.getInstance().client.GetStream().EndRead(res);
MailClient.AsyncState state = (MailClient.AsyncState)res.AsyncState;
string answer = Aes.DecryptStringFromBytes_Aes(state.buffer, state.AES_KEY, state.AES_IV);
if (answer.Contains("OK"))
{
string[] answer_params = answer.Split(',');
LoggedUserInfo.USER_ID = Convert.ToInt32(answer_params[1]);
LoggedUserInfo.USER_LOGIN = answer_params[2];
//zalogowano
//this.TargetWindow = new MessageListsWindow();
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new Action(() => this.TargetWindow = new MessageListsWindow()));
//System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => this.TargetWindow = new MessageListsWindow()));
}
else
{
//zle dane
System.Windows.MessageBox.Show("Zle dane");
}
}
catch(Exception exep) { }
}
这是 asyncSendEncryptedProtocolMessage 的声明
asyncSendEncryptedProtocolMessage(string message, AsyncCallback callBack)
使用功能
clientStream.BeginWrite(encryptedMessage, 0, encryptedMessage.Length, callBack, st);
当代码执行时出现异常“调用线程必须是 STA,因为许多 UI 组件都需要这个。” 我读到“SetApartmentState(ApartmentState.STA);” 但我不知道如何将其应用于回调。我也尝试过使用 STAThread 属性,但它不起作用。我使用 MVVM Light 框架。
堆栈跟踪
" w System.Windows.Threading.DispatcherObject.VerifyAccess()\r\n w System.Windows.Application.get_MainWindow()\r\n w MailClient.ViewModel.MainWindowModel.LoginInfo_recieved(IAsyncResult res) w c:\\Users\\oem\\Documents\\Visual Studio 2012\\Projects\\MvvmLight3\\MailClient\\ViewModel\\MainWindowModel.cs:wiersz 171"