为什么在更新调度程序中的进度条和标签时,异步任务需要花费更长的时间运行?

问题描述 投票:0回答:1

我正在创建一个程序,该程序使用SQL数据库中的值将大量文件从一个目录复制到另一个目录,以创建子文件夹和应放置在相应子文件夹中的文件。

我正在尝试更新进度条,以显示实际检查文件是否存在的异步任务的完成百分比,但是由于某种原因,如果我使用分派器更新和显示百分比,异步操作将花费更多时间。使用进度条的“ IsIndeterminate”属性时,异步操作会明显更快。

EX 1:更快地确定进度条码

Tuple<int, int> countsTuple = null;
Action exportFilesAction;
if (myChkbox.IsChecked.Value == true)
{
    moduleToExport = "p";
    downloadStatusLabel.Content = $"Exporting P{docsOrImages}...";
    progressBar.IsIndeterminate = true;
    exportFilesAction =
        () => countsTuple = dataExportUtilities.ExportData(sourcePath,
            destPath, logPath,
            moduleToExport,
            docsOrImages, selectedClientIDList, toExportAll, connString, buttonPressed,
            fileFound);
    await Task.Run(exportFilesAction);
    progressBar.IsIndeterminate = false;
    totalExported += countsTuple.Item1;
    totalNotExported += countsTuple.Item2;
}

对此相反:

使用标签更新进度百分比

Tuple<int, int> countsTuple = null;
Action getCountsAction;

if (myChkBox.IsChecked.Value == true)
{                                 
    moduleToExport = "p";
    exportFilesAction =
        () => countsTuple = dataExportUtilities.ExportData(sourcePath,
            destPath, logPath,
            moduleToExport,
            docsOrImages, selectedClientIDList, toExportAll, connString, buttonPressed,
            fileFound);
    var progress = new Progress<int>(value => progressBar.Value = value);
    await Task.Run(() =>
    {
        for (int i = 0; i < 100; i++)
        {
            ((IProgress<int>)progress).Report(i);
            Dispatcher.Invoke(()=>{
                 downloadStatusLabel.Content = $"({i})Exporting P {docsOrImages}...";
            });
            exportFilesAction();
        }
    });
    totalExported += countsTuple.Item1;
    totalNotExported += countsTuple.Item2;
}
c# wpf performance user-interface
1个回答
0
投票

正如JohnP在评论中指出的那样,第2版执行相同的操作100次。 Plus将更新调度到UI。

我认为您想进行深入的进度报告,在该报告中,每次文件的[[part完成时都会告诉用户某些更改。那不是那样的。您只能报告离散操作之间的进度。使用显示代码,例如,您可以在每个文件之后报告-每个事件一次。如果您想进行更详细的报告,则只有几个选项:

    找到实际执行更深入进度报告的dataExportUtilities.ExportData()版本。大概是一个事件。一些现代的Download / Upload / Copy类可以做到这一点,但这很少见。
  1. dataExportUtilities.ExportData()的内部循环进行反向工程,因此您可以在两行之间放置报告代码。
  2. 意识到这是更多的工作然后才值得,并且仅继续在文件之间进行报告。
  • 进行多任务处理/线程化的第一步(在给定范围内获得所有素数)时,我的优势在于,我首先编写了整个循环结构。因此,无论我需要多深地添加报告,都不是问题。
  • © www.soinside.com 2019 - 2024. All rights reserved.