use*_*597 1 c# wpf multithreading async-await
我正在编写一个 WPF 表单应用程序,在其中我尝试使用 Async await 方法循环遍历文件夹并实时显示其文件。在我的Task.Run()方法中,我正在引发我的事件,这引发了很好的事件,但是该事件代码还更新了一个位于UI 线程上的 TEXT BOX,因此我收到了 UI 线程错误
“调用线程不能访问这个对象,因为另一个线程拥有它。”
. 有什么方法可以更改我的代码以便我可以更新我的 TextBox?
private delegate void GetFilesCount(string f);
private event GetFilesCount onFileCount;
private void Btn_Compare_Click(object sender, RoutedEventArgs e)
{
onFileCount += FileCount;
CountFilesAsync();
}
function async void CountFilesAsync() {
await Task.Run(()=> {
System.IO.DirectoryInfo myDir = new System.IO.DirectoryInfo(path);
foreach (FileInfo item in myDir.GetFiles())
{
onFileCount(item.Name); // This is an EVENT
}
});
}
Run Code Online (Sandbox Code Playgroud)
和我的事件处理程序代码
private void FileCount(string fileName)
{
txtLabel_Log.Text = fileName; // < -- Calling Method UI Error
}
Run Code Online (Sandbox Code Playgroud)
小智 5
不确定这是否对您有帮助,但您可以尝试调用应用程序调度程序。
private void FileCount(string fileName)
{
Application.Current.Dispatcher.Invoke(() => {
txtLabel_Log.Text = fileName; // < -- Calling Method UI Error
});
}
Run Code Online (Sandbox Code Playgroud)