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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. cross thread operation not valid, when closing a windows form

cross thread operation not valid, when closing a windows form

Scheduled Pinned Locked Moved C#
winformsdesignhelp
16 Posts 5 Posters 3 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.
  • H Henry Minute

    Have a look at the link that 12Code gave you. I haven't looked at it, so don't know if it will help. If it doesn't help, feel free to come back.

    Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

    B Offline
    B Offline
    But_Im_a_Lady
    wrote on last edited by
    #6

    Thanks - will do Janet

    Lady Programmers are a rare breed!

    1 Reply Last reply
    0
    • 1 12Code

      The other thread that you created has directly update the form control, which is not allowed. You need to use Invoke. I have a thread might help you. http://www.codeproject.com/script/Forums/View.aspx?fid=1649&select=2972472&tid=2972413#xx2972472xx[^]

      ;)*12Code

      B Offline
      B Offline
      But_Im_a_Lady
      wrote on last edited by
      #7

      Thanks - will look at this & try & get it to work. Janet

      Lady Programmers are a rare breed!

      1 Reply Last reply
      0
      • 1 12Code

        The other thread that you created has directly update the form control, which is not allowed. You need to use Invoke. I have a thread might help you. http://www.codeproject.com/script/Forums/View.aspx?fid=1649&select=2972472&tid=2972413#xx2972472xx[^]

        ;)*12Code

        B Offline
        B Offline
        But_Im_a_Lady
        wrote on last edited by
        #8

        Just to prove your theory I commented out all references to 'faxing' (this was the other thread in my form) & I still get this error. So now I am confused:confused:

        Lady Programmers are a rare breed!

        1 Reply Last reply
        0
        • H Henry Minute

          Have a look at the link that 12Code gave you. I haven't looked at it, so don't know if it will help. If it doesn't help, feel free to come back.

          Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

          B Offline
          B Offline
          But_Im_a_Lady
          wrote on last edited by
          #9

          My first step was to comment out all references to 'faxing' (this was the other thread in my form) and I still get this error. So now I am confused:confused: Janet

          Lady Programmers are a rare breed!

          H 1 Reply Last reply
          0
          • B But_Im_a_Lady

            My first step was to comment out all references to 'faxing' (this was the other thread in my form) and I still get this error. So now I am confused:confused: Janet

            Lady Programmers are a rare breed!

            H Offline
            H Offline
            Henry Minute
            wrote on last edited by
            #10

            The only thing that makes any sense is as 12Code said in his OP. Somehow the 'faxing' thread is getting started, and then causes the error when you close the app. What sort of threading are you using? Is it a BackgroundWorker, or are you creating it in code? Whichever type, one way might be to handle the FormClosing event of your main form and close/de-activate the thread there.

            Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

            B 1 Reply Last reply
            0
            • B But_Im_a_Lady

              Hi All, After spending ages on google trying to understand & recify my problem, and having no success, I am hoping someone here can point me in the right direction. Here is my problem... I have a windows form, which has a selection of standard toolbox controls and custom User controls, some of which are added at design time & some of which are added at run time. This all works fine, but when I close the form I get this message:- "Cross-thread operation no valid: Control 'chkShowSparesMatrix' accessed from a thread other than the thread it was created on". This control is a standard MS check box which is added at design time. None of its properties are changed in code, the only event which is acted upon is 'checkedchanged':-

                  private void chkShowSparesMatrix\_CheckedChanged(object sender, EventArgs e)
                  {
                      if (chkShowSparesMatrix.Checked)
                      {
                          usrSparesMatrix1.IsStandAlone = false;
                          usrSparesMatrix1.Visible = true;
                      }
                      else
                      {
                          usrSparesMatrix1.IsStandAlone = false;
                          usrSparesMatrix1.Visible = false;
                      }
                  }
              

              If I remove this control, I get the same message on another control. If anyone can throw light on this for me I would be grateful, or if you need more info to understand my problem I can forward you this. Thanks in advance, Janet

              Lady Programmers are a rare breed!

              0 Offline
              0 Offline
              0x3c0
              wrote on last edited by
              #11

              What about the if-clause? Doesn't that access chkShowSparesMatrix?

              B 1 Reply Last reply
              0
              • H Henry Minute

                The only thing that makes any sense is as 12Code said in his OP. Somehow the 'faxing' thread is getting started, and then causes the error when you close the app. What sort of threading are you using? Is it a BackgroundWorker, or are you creating it in code? Whichever type, one way might be to handle the FormClosing event of your main form and close/de-activate the thread there.

                Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                B Offline
                B Offline
                But_Im_a_Lady
                wrote on last edited by
                #12

                I am using 'System.Threading', the code is below:-

                private void FaxEngineersRequest()
                {
                try
                {
                //SendZetaFax sendZetaFax = new SendZetaFax ();
                //sendZetaFax.FaxBody = _processingModule.CreateEngineerCallSheet ( _callNumber ).ToString ();
                //sendZetaFax.FaxNumber = usrAddressDetailsEngineer.Fax;
                //sendZetaFax.RecipientName = usrAddressDetailsEngineer.Contact;
                //sendZetaFax.From = _sysCNDR.Name;

                            ////Since the processing for Zeta fax can be v.slow - do processing on a separate thread.
                            //Thread thread = new Thread ( new ThreadStart ( sendZetaFax.SendFaxMessage ) );
                            //thread.Start ();
                        }
                        catch (Exception ex)
                        {
                            \_commonValidation.DisplayErrorGracefully ( ex );
                        }
                    }
                

                As you can see I have commented this part of the code out - so it will never run, but I still get the cross thread operation not valid error. <blockquote class="FQ"><div class="FQA">Henry Minute wrote:</div>Whichever type, one way might be to handle the FormClosing event of your main form and close/de-activate the thread there. </blockquote> Not quite sure how / if / why I need to do this :confused: Janet

                Lady Programmers are a rare breed!

                H 1 Reply Last reply
                0
                • 0 0x3c0

                  What about the if-clause? Doesn't that access chkShowSparesMatrix?

                  B Offline
                  B Offline
                  But_Im_a_Lady
                  wrote on last edited by
                  #13

                  Yeah I suppose it does. Even if I comment out the single method which uses System.Threading to send a fax (this method isn't always called in code anyway), I still get the 'cross threading operation not valid error message. I have no idea why:confused:

                  Lady Programmers are a rare breed!

                  1 Reply Last reply
                  0
                  • B But_Im_a_Lady

                    I am using 'System.Threading', the code is below:-

                    private void FaxEngineersRequest()
                    {
                    try
                    {
                    //SendZetaFax sendZetaFax = new SendZetaFax ();
                    //sendZetaFax.FaxBody = _processingModule.CreateEngineerCallSheet ( _callNumber ).ToString ();
                    //sendZetaFax.FaxNumber = usrAddressDetailsEngineer.Fax;
                    //sendZetaFax.RecipientName = usrAddressDetailsEngineer.Contact;
                    //sendZetaFax.From = _sysCNDR.Name;

                                ////Since the processing for Zeta fax can be v.slow - do processing on a separate thread.
                                //Thread thread = new Thread ( new ThreadStart ( sendZetaFax.SendFaxMessage ) );
                                //thread.Start ();
                            }
                            catch (Exception ex)
                            {
                                \_commonValidation.DisplayErrorGracefully ( ex );
                            }
                        }
                    

                    As you can see I have commented this part of the code out - so it will never run, but I still get the cross thread operation not valid error. <blockquote class="FQ"><div class="FQA">Henry Minute wrote:</div>Whichever type, one way might be to handle the FormClosing event of your main form and close/de-activate the thread there. </blockquote> Not quite sure how / if / why I need to do this :confused: Janet

                    Lady Programmers are a rare breed!

                    H Offline
                    H Offline
                    Henry Minute
                    wrote on last edited by
                    #14

                    If your 'faxing' thread does not run, and it certainly shouldn't from the code you posted, then there has to be another thread running to cause the exception. If you don't know about this thread, you obviously cannot close it in the FormClosing handler. You might however put a break point there and use the debugger to search for the 'Thread With No Name'. I would suggest Googling for 'Debugging Threads C#' for methods to do this. As always, come back if no joy.

                    Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                    B 1 Reply Last reply
                    0
                    • B But_Im_a_Lady

                      Hi All, After spending ages on google trying to understand & recify my problem, and having no success, I am hoping someone here can point me in the right direction. Here is my problem... I have a windows form, which has a selection of standard toolbox controls and custom User controls, some of which are added at design time & some of which are added at run time. This all works fine, but when I close the form I get this message:- "Cross-thread operation no valid: Control 'chkShowSparesMatrix' accessed from a thread other than the thread it was created on". This control is a standard MS check box which is added at design time. None of its properties are changed in code, the only event which is acted upon is 'checkedchanged':-

                          private void chkShowSparesMatrix\_CheckedChanged(object sender, EventArgs e)
                          {
                              if (chkShowSparesMatrix.Checked)
                              {
                                  usrSparesMatrix1.IsStandAlone = false;
                                  usrSparesMatrix1.Visible = true;
                              }
                              else
                              {
                                  usrSparesMatrix1.IsStandAlone = false;
                                  usrSparesMatrix1.Visible = false;
                              }
                          }
                      

                      If I remove this control, I get the same message on another control. If anyone can throw light on this for me I would be grateful, or if you need more info to understand my problem I can forward you this. Thanks in advance, Janet

                      Lady Programmers are a rare breed!

                      L Offline
                      L Offline
                      Luc Pattyn
                      wrote on last edited by
                      #15

                      Hi, here is my standard reply on cross-thread problems, I hope it helps: Controls are not thread-safe, hence they should be touched (that is: their methods or properties called) only by the thread that created them, which normally is the main thread (aka GUI thread). Creating some controls on a different thread is unlikely to be successful, since all Controls get linked somehow: they reside on Forms, Forms are related to each other (by Parent, by Z-Order, etc), so normally all are created on a single thread. If you violate the “don’t touch Controls from another thread” rule and are running .NET version 2.0 or above you will get an InvalidOperationException (“Cross-thread operation not valid”), which should be remedied by changing the code. Do not set Control.CheckForIllegalCrossThreadCalls false, since that does hide the exception but does not cure the fundamental flaw in your code, so it just postpones the moment of failure, which typically will show as a non-responsive and possibly badly painted GUI. Here are some ways to get another thread: - explicitly launching a Thread instance - exclicitly delegating some work to a ThreadPool thread - using a BackgroundWorker; a BGW is a separate thread with the advantage that two of its events (ProgressChanged and RunWorkerCompleted) execute on the GUI thread; however the bulk of the work normally is handled in the DoWork handler which runs on a distinct thread. - using timers other than System.Windows.Forms.Timer; the Forms timer ticks on the GUI thread, all other use different threads to handle the periodic event; - using asynchronous input/output, such as the DataReceived event of the SerialPort class Any of these touching a single method or property of a Control is sufficient to create havoc; there are 5 exceptions: - the InvokeRequired property - the Invoke, BeginInvoke, EndInvoke and CreateGraphics methods (the latter only if the handle for the control has already been created). If there is a need to touch the Control from another thread, one must use an Invoke pattern, which basically looks like this:

                      public void SetText(string text) {
                      if (myControl.InvokeRequired) {
                      // this runs on the foreign thread and causes the
                      // invocation of this same method on the GUI thread
                      myControl.Invoke(new Action< string >(SetText),
                      new object[] {text});
                      } else {
                      // this runs on the GUI thread only
                      myControl.Text=text;
                      }
                      }

                      :)

                      Luc Pat

                      1 Reply Last reply
                      0
                      • H Henry Minute

                        If your 'faxing' thread does not run, and it certainly shouldn't from the code you posted, then there has to be another thread running to cause the exception. If you don't know about this thread, you obviously cannot close it in the FormClosing handler. You might however put a break point there and use the debugger to search for the 'Thread With No Name'. I would suggest Googling for 'Debugging Threads C#' for methods to do this. As always, come back if no joy.

                        Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                        B Offline
                        B Offline
                        But_Im_a_Lady
                        wrote on last edited by
                        #16

                        For completeness of this message - I have now fixed my problem. I made a STUPID :doh: mistake... Rushing to finish the project I had put Close() inside the formclosing event!!! Won't be doing that again in a hurry :)

                        Lady Programmers are a rare breed!

                        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