【问题标题】:How to Prevent 'UI Freeze by using .GetFiles in WPF' [duplicate]如何通过在 WPF 中使用 .GetFiles 来防止“UI 冻结”[重复]
【发布时间】:2019-08-21 15:05:56
【问题描述】:

这是一个比较两个文件夹内容的功能。

问题:

使用 System.IO.DirectoryInfo.GetFiles() 时,应用程序冻结(15 sec),我知道那是因为它使用的是主线程……它是 10 GB。

我不使用线程、同步或其他的原因是因为我需要 主线程中的“fileInfosToCopy”列表,所以当我要使用线程时 不能再访问了。

有什么想法吗?我只需要主线程中的“fileInfosToCopy”列表。

string pathA = @"\\server\share\folder";
string pathB = @"C:\folder";


public void Scan()
    {
        try
        {
            string Computer = "server";
            Ping ping = new Ping();
            PingReply reply = ping.Send(Computer);

            if (reply.Status == IPStatus.Success)
            {

                var netwerkfolder = new DirectoryInfo(pathA);
                var localfolder = new DirectoryInfo(pathB);

                var networkfiles = netwerkfolder.GetFiles("*.*", SearchOption.AllDirectories);
                var localfiles = localfolder.GetFiles("*.*", SearchOption.AllDirectories);

                var listmissingfiles = networkfiles.Select(s => s.Name).ToList().Except(localfiles.Select(s => s.Name)).ToList();

                var fileInfosToCopy = new List<FileInfo>();

                foreach (var info in networkfiles)
                {
                    if (listmissingfiles.Contains(info.Name))
                    {
                        fileInfosToCopy.Add(info);

                    }
                }
            }
            else
            {
              // not connected
            }
        }
        catch (Exception)
        {
          // x
        }
    }
}

【问题讨论】:

  • 将扫描重构为返回文件信息列表的任务。然后,您可以等待您的任务,它将在单独的线程上运行,返回您的列表,然后您可以在等待之后的行中使用该列表做任何您想做的事情。 Async Await 和 Task 非常有用。你可以在这里开始你的研究docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
  • 还可以考虑使用EnumerateFiles 而不是GetFiles。您可以在所有文件都返回之前开始处理文件。

标签: c# wpf multithreading


【解决方案1】:

您可以通过以下方式访问它:

Application.Current.Dispatcher.Invoke(() => fileInfosToCopy.Add(info));

fileInfosToCopy 将存在于该方法之外并由主线程创建(就像您最初可能拥有的那样)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多