如何从异步方法回调中更新c#wpf中的gui
本文关键字:更新 c#wpf 中的 gui 回调 异步方法 | 更新日期: 2023-09-27 18:09:54
我在stackoverflow和net上搜索过,但找不到问题的解决方案。
我以异步方式从流中读取。我想回调以更新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框架。
StackTrace
" 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"
public static void Dispatch(this DispatcherObject source, Action func)
{
if (source.Dispatcher.CheckAccess())
func();
else
source.Dispatcher.Invoke(func);
}
然后像这样使用:
MailClient.Helpers.Client.getInstance()
.asyncRecieveEncryptedProtocolMessage(new AsyncCallback(()=>
Application.Current.MainWindow.Dispatch(LoginInfo_recieved)));