我正在将一个项目从winforms转换到WPF。当我的代码基于WinForms时,我使用(this.InvokeRequired)来检查线程是否具有访问权限。现在我使用以下基于我的Mainform的代码:
// this is the delegate declaration to Allow Background worker thread to write to Log Output
delegate void LogUpdateCallBack(String LogMessage);
// method to update the Log Window from the Background Thread
public void LogUpdate(String LogMessage)
{
Console.WriteLine("Entering");
if (!Application.Current.Dispatcher.CheckAccess())
{
Console.WriteLine("Thread doesn't have UI access");
LogUpdateCallBack callback = new LogUpdateCallBack(LogUpdate);
Application.Current.Dispatcher.Invoke(callback, LogMessage);
}
else
{
Console.WriteLine("Thread has UI access");
listBox_Output.Items.Add(LogMessage);
Console.WriteLine(LogMessage);
// listBox_Output.TopIndex = listBox_Output.Items.Count - 1;
}
Console.WriteLine("Exiting");
}
我遇到的问题是Listbox没有更新。没有错误或异常,我尝试更新其他UI控件。LogMessage正在写入输出窗口,所以我很困惑。
这是样例控制台输出:
Entering
Thread doesn't have UI access
Entering
Thread has UI access
My LogMessage is output here
Exiting
Exiting
Entering
Thread doesn't have UI access
Entering
Thread has UI access
My LogMessage is output here
Exiting
Exiting
我尝试更新其他UI控件,只是为了检查是否与我的Listbox有问题,但没有成功。
除了切换到CheckAccess()之外,在新的WPF代码中我所做的唯一其他重大更改是将在后台工作器中运行的所有代码都基于另一个类。我不确定这是否可能是问题的一部分?
--
我尝试了你的想法:
Application.Current.Dispatcher.BeginInvoke(new LogUpdateCallBack(LogUpdate), LogMessage)
然而,我的列表框仍未更新,如果我输出
Console.WriteLine(listBox_Output);
我看到列表框数组在增长:
System.Windows.Controls.ListBox Items.Count:2020
System.Windows.Controls.ListBox Items.Count:2021
System.Windows.Controls.ListBox Items.Count:2022
System.Windows.Controls.ListBox Items.Count:2023
System.Windows.Controls.ListBox Items.Count:2024
System.Windows.Controls.ListBox Items.Count:2025
但是表单没有变化。这非常令人困惑!