【发布时间】:2018-04-26 11:57:02
【问题描述】:
我正在尝试更新线程内不同类的 UI。
相关代码为:
MainWindow.xaml.cs
private void encryptButtonPressed(object sender, RoutedEventArgs e)
{
if (checkValues() == true)
{
updateConsole("Starting Encryption...");
Thread encryptThread = new Thread(encrypt);
encryptThread.Start();
}
}
加密函数
public void encrypt()
{
Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
encrypt.start();
}
更新控制台功能
public void updateConsole(String text)
{
consoleWindow.AppendText(Environment.NewLine);
consoleWindow.AppendText(text);
consoleWindow.ScrollToEnd();
}
Encrypt.cs
public byte[] key;
public String source;
public String destination;
public MainWindow mainWindow;
public Encrypt(byte[] key, String source, String destination, MainWindow mainWindow)
{
this.key = key;
this.source = source;
this.destination = destination;
this.mainWindow = mainWindow;
}
启动函数
public void start()
{
mainWindow.updateConsole("Updating form thread");
}
我试过了
Dispatcher.Invoke(() =>
{
mainWindow.updateConsole("Updating form thread");
});
但没用。
【问题讨论】:
-
but no use.是什么意思? -
这意味着我尝试的最后一件事不起作用。
-
“不起作用”是什么意思?你什么也没看到,一个错误,它崩溃了吗?
-
即使使用
Dispatcher.Invoke也会出现异常吗?错误是什么? -
我已经尝试
Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => this.mainWindow.updateConsole(s)));并且它正在工作。
标签: c# wpf multithreading