Frage

I am making a program which finds duplicate files in a directory, but when the directory it is searching has too many of those files it will crash the application. I was wondering if there is a way to buffer the amount of files it grabs. Here is the code that does the thing I am explaining:

string[] filePathsb = Directory.GetFiles(
      @"" + Dirfind, "*" + filetyperest, SearchOption.AllDirectories);

for (int i = 0; i < filePathsb.Length; i++)
   {

     ListBoxItem itm = new ListBoxItem();

     try
     {
        List<TodoItem> items = new List<TodoItem>();

        filelistboxitem.Items.Add(new TodoItem() { Title = "" + filePathsb[i], Deletea = "" + i });
     }
     catch (Exception ex)
     {
        System.Windows.Forms.MessageBox.Show("Error occurance: " + ex);
     }

}

Just a note: this works fine when there are about < 50 files.

War es hilfreich?

Lösung

WinForms can become quite slow and unresponsive if you add many items to a ListBox. This is particularly true if, as in your example, you do the adding from the UI thread. The UI will freeze up until the last item is added.

What can I do?

A simple improvement is to call

SuspendLayout();

before your loop starts, and

ResumeLayout();

after the loop completes. That will reduce the cost of updating the listbox, so the whole thing completes faster.

How Can I Prevent Locking the UI Entirely?

You can use threading to update the list in the background. For WinForms, BackgroundWorker is commonly used. Note that you cannot directly update the UI from the BackgroundWorker, as they run on different threads. The usual event mechanism ReportProgress does not apply in this situation, since you want to continually update the UI until all files are loaded. Instead, you can use the approach outlined here:

Accessing UI Control from BackgroundWorker Thread

Andere Tipps

Try using the Backgroundworker thread for finding files.your UI will not freeze then and file finding logic will run in 'background'

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top