-1

This is a fuction that compare the contents of two folders.

Issue:

When using System.IO.DirectoryInfo.GetFiles() the application is freezing (15 sec), I know that's because it's using the main thread... it's 10 GB.

The reason why I'm not using a thread, sync or whatever is because I need the "fileInfosToCopy" list in by main thread, so when I'm going to use a thread I can not access it anymore.

Any ideas? I only need the "fileInfosToCopy" list in my main thread.

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
        }
    }
}
Justaboi
  • 13
  • 4
  • Refactor scan into a Task that returns a List of fileinfo. You can then await your task and it'll run on a separate thread, return your list and you do whatever you want with that list on the line after the await. Async Await and Task are very useful. You could start your research here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types – Andy Aug 21 '19 at 15:18
  • Also consider using `EnumerateFiles` instead of `GetFiles`. You can start processing the file before all of them have been returned. – Chris Dunaway Aug 21 '19 at 20:44

1 Answers1

0

You could access it by using:

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

Where fileInfosToCopy would exist outside of that method and be created by the main thread (as you probably had it originally).

Chris Mack
  • 5,148
  • 2
  • 12
  • 29