且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

后台工作者在WPF中无法正常工作

更新时间:2023-02-01 15:15:05

跟随代码,您完全破坏了在后台线程上进行工作的目的.

在后台线程的DoWork方法中,您告诉UI线程(this.Dispatcher.Invoke)执行长时间运行的代码,完全删除了后台线程的要点.

后台线程应该是调用将文件添加到datagrid的方法.

我相信您正在寻找这样的东西:

Following your code, you completely wrecked the purpose of doing work on a background thread.

In the DoWork method, on a background thread, you told the UI thread (this.Dispatcher.Invoke) to execute the long running code, completely removing the point of the background thread.

The background thread should be Invoking a method to add the file to the datagrid.

I believe you''re looking for something like this:

void _background_DoWork(object sender, DoWorkEventArgs e)
{
        FileInfo[] files = new     
        DirectoryInfo(System.IO.Path.GetTempPath()).GetFiles();
       
        foreach (FileInfo fi in files)
        {
            if (fi != null)              
            {                 
                this.Dispatcher.BeginInvoke((Action)(() => dataGrid1.Items.Add(fi)));
            }
        }
    }
}


您好,

您应该在后台工作器的主循环中添加一小段睡眠,以允许UI线程刷新显示.

尝试在您的foreach循环中添加类似的内容
Hello,

You should add to the background worker a short sleep in its main loop to allow the UI thread to refresh the display.

Try adding something like this to your foreach loop
// This sleep will allow the UI thread to refresh the display.
totalCounter++;
if (totalCounter % 100 == 0)
    System.Threading.Thread.Sleep(80);