locked
how to solve cross thread error in C#.NET

    Question

  •  Our  project is “download manager” How to terminate Thread execution and also How to execute next step/statements after that terminated thread.

         following line of coding I have problem face.

    We use  thread  thrDownload”

    MessageBox.Show("File Downloading Completed.");

          //thrDownload.Abort();

          Thread.Sleep(100);

          btnpause_resume.Enabled = false;  //For Pause/Resume Button

          lblspeed.Visible = false;

          lbltimeleft.Visible = false;

          lblremainingsize.Visible = false;

          lblProgress.Visible = false;

          button2.Enabled = true; // For Exit Button

     

    After message File Downloading Completed.

    We get error as –

    Cross-thread operation not valid: Control 'btnpause_resume' accessed from a thread other than the thread it was created on.

     

    We use Thread.Sleep, thrDownload.Abort to terminate the current running thread.,

    But The problem is that,we want the statements to execute  after the message File Downloading Completed.

     

    btnpause_resume.Enabled = false;  //For Pause/Resume Button

    lblspeed.Visible = false;

    lbltimeleft.Visible = false;

    lblremainingsize.Visible = false;

    lblProgress.Visible = false;

    button2.Enabled = true; // For Exit Button

     

    So Please suggest me how  to stop the current thread & execute the next statements.

     

     

     please can u give in code solution as early as possible

    Thank You
    Wednesday, May 16, 2007 12:27 PM

All replies

  • http://msdn2.microsoft.com/en-us/library/y32y8wtd(VS.80).aspx 

     

    Whenever possible, execute the methods of a control only on the thread with which it was created. If you must call a method of a control from another thread, you must use the Invoke to call the method.

     

    Also look into using the user friendly "BackroundWorker" control. This has built in "Complete", "Update" and "DoWork" methods. You can update your form control properties on the BackroundWorker Complete event.

     

    http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx 

     

     

     

    Hope this helps. Smile

    Wednesday, May 16, 2007 1:12 PM
  • In concreto your workcompleted method could look like:

    Code Snippet

    WorkComplete(string message)
    {
     if (this.InvokeRequred)
     {
      this.EndInvoke(this.BeginInvoke(new MethodInvoker(delegate() { WorkComplete(message); } )));
     }
     else
     {
      MessageBox.Show(message);
      btnpause_resume.Enabled = false;
      lblspeed.Visible = false;
      lbltimeleft.Visible = false;
     ....
     }
    }



    Wednesday, May 16, 2007 2:51 PM