【问题标题】:Access UI Control on UI Thread using async & a event使用异步和事件访问 UI 线程上的 UI 控件
【发布时间】: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


    【解决方案1】:

    不确定这是否会对您有所帮助,但您可以尝试调用您的应用程序调度程序。

    private void FileCount(string fileName)
    {
            Application.Current.Dispatcher.Invoke(() => {
                txtLabel_Log.Text = fileName;   // < -- Calling Method UI Error
            });
    }
    

    【讨论】:

    • 你不是白痴,我们都必须学习一些方法。很高兴您的问题得到解决
    【解决方案2】:

    Async in 4.5: Enabling Progress and Cancellation in Async APIs

    private void Btn_Compare_Click(object sender, RoutedEventArgs e)
    {
        CountFilesAsync(Progress<string>(FileCount));
    }
    
    private async void CountFilesAsync(IProgress<string> progress)
    {
        await Task.Run(() =>
            {
                System.IO.DirectoryInfo myDir = new System.IO.DirectoryInfo(path);
                foreach (FileInfo item in myDir.GetFiles())
                {
                    progress(item.Name); // report progress
                } 
            });
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多