【发布时间】:2018-03-23 15:47:34
【问题描述】:
我正在编写一个 WPF 表单应用程序,在其中我尝试使用异步等待方法循环遍历文件夹并实时显示其文件。在我的 Task.Run() 方法中,我正在引发我的事件,这很好,但是该事件代码也 更新了一个文本框,它在 UI 线程 上,因此我收到 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
}
});
}
和我的事件处理程序代码
private void FileCount(string fileName)
{
txtLabel_Log.Text = fileName; // < -- Calling Method UI Error
}
【问题讨论】:
标签: c# wpf multithreading async-await