Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Main thread freezing while running a separate thread

Main thread freezing while running a separate thread

Scheduled Pinned Locked Moved C#
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    ShadowUz
    wrote on last edited by
    #1

    Hello. I have a programm that scans the selected folder and adds all the files' names to the listbox. I'm running the scan function in a separate thread. But, still the main form is freezing. Here is my code:

    private void button2_Click(object sender, EventArgs e)

        {
            Thread mThread = new Thread(myThread);
            myThread.Start();
        }
    

    public void myThread()
    {
    AddFiles(label1.Text);
    }

    public void AddFiles(string targetDirectory)
    {

            if (listBox1.InvokeRequired)
            {
                AddFilesAdd method = new AddFilesAdd(AddFiles);
                listBox1.Invoke(method, new object\[\] { targetDirectory });
                return;
            }
    
            if (progressBar1.InvokeRequired)
            {
                AddFilesAdd method = new AddFilesAdd(AddFiles);
                progressBar1.Invoke(method, new object\[\] { targetDirectory });
                return;
            }
            string\[\] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
            {
                this.listBox1.Items.Add(fileName);
                progCounter++;
                progressBar1.Value = progCounter;
                
            }
    
            // Recurse into subdirectories of this directory.
            string\[\] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
            {
                numberOfFolders++;
                AddFiles(subdirectory);
                
            }
    
    L 1 Reply Last reply
    0
    • S ShadowUz

      Hello. I have a programm that scans the selected folder and adds all the files' names to the listbox. I'm running the scan function in a separate thread. But, still the main form is freezing. Here is my code:

      private void button2_Click(object sender, EventArgs e)

          {
              Thread mThread = new Thread(myThread);
              myThread.Start();
          }
      

      public void myThread()
      {
      AddFiles(label1.Text);
      }

      public void AddFiles(string targetDirectory)
      {

              if (listBox1.InvokeRequired)
              {
                  AddFilesAdd method = new AddFilesAdd(AddFiles);
                  listBox1.Invoke(method, new object\[\] { targetDirectory });
                  return;
              }
      
              if (progressBar1.InvokeRequired)
              {
                  AddFilesAdd method = new AddFilesAdd(AddFiles);
                  progressBar1.Invoke(method, new object\[\] { targetDirectory });
                  return;
              }
              string\[\] fileEntries = Directory.GetFiles(targetDirectory);
              foreach (string fileName in fileEntries)
              {
                  this.listBox1.Items.Add(fileName);
                  progCounter++;
                  progressBar1.Value = progCounter;
                  
              }
      
              // Recurse into subdirectories of this directory.
              string\[\] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
              foreach (string subdirectory in subdirectoryEntries)
              {
                  numberOfFolders++;
                  AddFiles(subdirectory);
                  
              }
      
      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Hi, your code looks a bit weird to me. Here are some comments: 1. AddFiles(label1.Text); is strictly not OK, you are touching a Control from a thread other than the main one. A better approach is to read label1.Text before launching the thread, then pass the string to it somehow (class member, or ThreadStart parameter). 2. the progressbar code will never execute: progressBar1.InvokeRequired and listBox1.InvokeRequired are bound to have the same value, so either the first if block's return will fire, or both if blocks will be skipped. 3. the whole threading approach is flawed: there really isn't any code running on the separate thread, all it does is cause the outermost AddFiles() to run on the main thread, so the hierarchical scan is all on the main thread (which will be very busy and uncapable of serving the GUI). Solution: split the action in two parts, the first part scanning the file system and storing strings in a collection (all on the separate thread), the second part adding the collection's content to the ListBox. 4. Lastly, this is a typical job a BackgroundWorker is good at. It would do the scanning in the DoWork handler, and the ListBox updating in the RunWorkerCompleted handler. You wouldn't need to call Invoke at all, the BGW does that for you. PS: you may want to read this my little article[^] on the matter. :)

      Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups