none
C# ==> Threading ==> Form Stuck ?!??!?!?! RRS feed

  • Question

  • I have a form
    In this form I have a progress bar
    i also have a function named startIt()
    startItit has a loop that counts from 0 to 30, and after each count it adds 1 to the value of the progressbar.
    everything works except the form gets stock while counting until 30
    I used a thread and still same problem form is stuck

    Thread t = new thread(new threadStart(startIt)); 
    t.start(); 
     
    public delegate void del(); 
    public void startIt() 
         if (!invokeRequired) 
         { 
               for (int i=0; i<30 ; i++) 
              { 
                  System.Threading.Thread.Sleep(1000); 
                  progressBar.value++; 
              } 
         } 
         else 
         { 
              del d = new del(StartIt); 
              BeginInvoke(d); 
         } 

    Why is my form getting stuck even though the code is running on a separate thread?
    Anything i'm doing wrong?
    thank you

    AG
    • Edited by aryaxt Friday, November 14, 2008 10:58 PM
    • Moved by Jenny Lo Monday, November 17, 2008 9:29 PM (Moved from .NET Services - Technical Discussions to Visual Studio Report Controls)
    Friday, November 14, 2008 10:56 PM

Answers

  • I solved the problem.
    In the example above i'm runing the whole point of threadsby the if statement that checks if invoke is required or not.
    and since invoke is required the whole code runs on the main thread. (not what i want to do)
    so what i did was to remove the if statement
    and if a part of the code requires to be invoked (adding 1 to the value of the progress bar)
    i created a function and delegate to do that and i call it inside the thread i just made
    working code is below:

    Thread t = new thread(new threadStart(startIt));  
    t.start();  
      
     
    public void startIt()  
    {  
         for (int i=0; i<30 ; i++)  
         {  
             System.Threading.Thread.Sleep(1000);  
             AddToProgress(); 
         }  
    }  
     
    public delegate void del(); 
    public void AddToProgress() 
         if(!invokeRequired) 
         { 
              progressBar.value++; 
         } 
         else 
         { 
              del AddToProgressD = new del(AddToProgress); 
              BeginInvoke(AddToProgressD); 
         } 


    AG
    • Marked as answer by aryaxt Saturday, November 15, 2008 5:30 AM
    Saturday, November 15, 2008 5:30 AM