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. Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

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

Scheduled Pinned Locked Moved C#
helpquestioncsharptutorial
8 Posts 5 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.
  • P Offline
    P Offline
    parth p
    wrote on last edited by
    #1

    Hi there, I am creating my first multi threading app. And I now I'm stuck on here. Here's my Code: public partial class FrmMain : Form { Thread threadVBNums, threadCNum; private void StartProcess() { this.threadVBNums = new Thread(new ThreadStart(this.AddVbNums)); this.threadVBNums.Start(); this.threadCNums = new Thread(new ThreadStart(this.AddCNums)); this.threadCNums.Start(); } private void AddVbNums() { for(int i = 0; i < 20, i++) { this.vbText.Text += ("Main thread: {0}\n", i); } } private void AddCNums() { for(int i = 0; i < 20, i++) { this.cText.Text += ("Main thread: {0}\n", i); } } } And this is written in Windows Application. So the other code is same as normal CS app. code. Now this gives me an error saying

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

    I know that .NET do not allow me access controls on form. But I don't know how to solve this??!! Can someone tell me what is happening wrong and how to solve it??

    - Stop thinking in terms of limitations and start thinking in terms of possibilities -

    L C H 3 Replies Last reply
    0
    • P parth p

      Hi there, I am creating my first multi threading app. And I now I'm stuck on here. Here's my Code: public partial class FrmMain : Form { Thread threadVBNums, threadCNum; private void StartProcess() { this.threadVBNums = new Thread(new ThreadStart(this.AddVbNums)); this.threadVBNums.Start(); this.threadCNums = new Thread(new ThreadStart(this.AddCNums)); this.threadCNums.Start(); } private void AddVbNums() { for(int i = 0; i < 20, i++) { this.vbText.Text += ("Main thread: {0}\n", i); } } private void AddCNums() { for(int i = 0; i < 20, i++) { this.cText.Text += ("Main thread: {0}\n", i); } } } And this is written in Windows Application. So the other code is same as normal CS app. code. Now this gives me an error saying

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

      I know that .NET do not allow me access controls on form. But I don't know how to solve this??!! Can someone tell me what is happening wrong and how to solve it??

      - Stop thinking in terms of limitations and start thinking in terms of possibilities -

      L Offline
      L Offline
      lsconyer
      wrote on last edited by
      #2

      To avoid this problem, I would suggest you use a BackgroundWorker. This component will handle much of the threading for you and allow you a way modify controls on the form. It has a few very helpful methods...RunWorkerAsync() , ReportProgress(), and WorkDone(). You can call the ReportProgress method within your for loop like private void StartProcess() { this.bgWorker.RunWorkerAsync(); } private void bgWorker_DoWork() { AddCNums(); } private void AddCNums() { for(int i = 0; i < 20, i++) { this.bgWorker.ReportProgress(0, i)} } } private void bgWorker_ReportProgress(object sender, ProgressChangedEventArgs e) { if(e.ProgressPercentage == 0) { int i = (int)e.UserState; this.cText.Text += ("Main thread: {0}\n", i); } } It's very clean.

      Lester http://www.lestersconyers.com

      1 Reply Last reply
      0
      • P parth p

        Hi there, I am creating my first multi threading app. And I now I'm stuck on here. Here's my Code: public partial class FrmMain : Form { Thread threadVBNums, threadCNum; private void StartProcess() { this.threadVBNums = new Thread(new ThreadStart(this.AddVbNums)); this.threadVBNums.Start(); this.threadCNums = new Thread(new ThreadStart(this.AddCNums)); this.threadCNums.Start(); } private void AddVbNums() { for(int i = 0; i < 20, i++) { this.vbText.Text += ("Main thread: {0}\n", i); } } private void AddCNums() { for(int i = 0; i < 20, i++) { this.cText.Text += ("Main thread: {0}\n", i); } } } And this is written in Windows Application. So the other code is same as normal CS app. code. Now this gives me an error saying

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

        I know that .NET do not allow me access controls on form. But I don't know how to solve this??!! Can someone tell me what is happening wrong and how to solve it??

        - Stop thinking in terms of limitations and start thinking in terms of possibilities -

        C Offline
        C Offline
        carbon_golem
        wrote on last edited by
        #3

        You'll have to add a Method to handle it that looks something like this...private delegate void TextBoxUpdater(TextBox t, String s); private void UpdateTextBox(TextBox t, String s){ if(t.InvokeRequired) { t.Invoke(new TextBoxUpdater(UpdateTextBox), Object[]{t, s})); } else { t.Text = s; } }
        Call this from your thread routine in place of manually setting the control text. The above code may not work, I didn't compile it, but you get the idea. You have to check "InvokeRequired" on a control that you want to cross thread, and call the updating method on the UI thread using a delegate. Scott

        "Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand

        1 Reply Last reply
        0
        • P parth p

          Hi there, I am creating my first multi threading app. And I now I'm stuck on here. Here's my Code: public partial class FrmMain : Form { Thread threadVBNums, threadCNum; private void StartProcess() { this.threadVBNums = new Thread(new ThreadStart(this.AddVbNums)); this.threadVBNums.Start(); this.threadCNums = new Thread(new ThreadStart(this.AddCNums)); this.threadCNums.Start(); } private void AddVbNums() { for(int i = 0; i < 20, i++) { this.vbText.Text += ("Main thread: {0}\n", i); } } private void AddCNums() { for(int i = 0; i < 20, i++) { this.cText.Text += ("Main thread: {0}\n", i); } } } And this is written in Windows Application. So the other code is same as normal CS app. code. Now this gives me an error saying

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

          I know that .NET do not allow me access controls on form. But I don't know how to solve this??!! Can someone tell me what is happening wrong and how to solve it??

          - Stop thinking in terms of limitations and start thinking in terms of possibilities -

          H Offline
          H Offline
          half life
          wrote on last edited by
          #4

          The "Tricky" way is just like carbon_golem suggested (and this is the correct way, u need to thank golem :):) ) the simple way and not recommended is override this by only changing the CheckForIllegalCrossThreadCalls property to false : CheckForIllegalCrossThreadCalls = false; :) :)

          Have Fun Never forget it

          P L 2 Replies Last reply
          0
          • H half life

            The "Tricky" way is just like carbon_golem suggested (and this is the correct way, u need to thank golem :):) ) the simple way and not recommended is override this by only changing the CheckForIllegalCrossThreadCalls property to false : CheckForIllegalCrossThreadCalls = false; :) :)

            Have Fun Never forget it

            P Offline
            P Offline
            parth p
            wrote on last edited by
            #5

            Thank you very much half-life. :):) But is it really safe to do?? I mean what you suggested did work 100% but I read on Internet that this is used for Debugging, just to avoid error messages! :confused: I think someone should write article about Multi-threading on CP. I searched but didn't find any.

            - Stop thinking in terms of limitations and start thinking in terms of possibilities -

            modified on Monday, April 7, 2008 2:52 PM

            H 1 Reply Last reply
            0
            • P parth p

              Thank you very much half-life. :):) But is it really safe to do?? I mean what you suggested did work 100% but I read on Internet that this is used for Debugging, just to avoid error messages! :confused: I think someone should write article about Multi-threading on CP. I searched but didn't find any.

              - Stop thinking in terms of limitations and start thinking in terms of possibilities -

              modified on Monday, April 7, 2008 2:52 PM

              H Offline
              H Offline
              half life
              wrote on last edited by
              #6

              Nothing is Stupid When u do not know it The Property is MS Idea so it's probebly doable The right way goes like this: //Declare a Deleagte for the type of the Function u will use //see that that if i had an //public void function() //so the declartion of the deleage would look like this : //public delegate void RefToFunction(); //without the parameter **public delegate void RefToFunction(string s);** //create an instance of the delegate like this: // and give it the function u like to invoke **RefToFunction handle = new RefToFunction(UpdateTextBox);** //declare the param an wrap it in a object array **string s = "Test"; object[] param = { s };** //Invoke with the handle and the param //where u need to invoke it //if u did not have any param so just : //this.Invoke(handle); **this.Invoke(handle, param);** //the implemntation of the function **public static void UpdateTextBox(string s) { MessageBox.Show(s); }ode> i did a lot of research about this so i hope i helped if u need any clarification just reply :):) Have Fun Never forget it **

              1 Reply Last reply
              0
              • H half life

                The "Tricky" way is just like carbon_golem suggested (and this is the correct way, u need to thank golem :):) ) the simple way and not recommended is override this by only changing the CheckForIllegalCrossThreadCalls property to false : CheckForIllegalCrossThreadCalls = false; :) :)

                Have Fun Never forget it

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

                don't set CheckForIllegalCrossThreadCalls false, this is a terrible hack, that WILL result in malfunction, sooner or later (sooner if you are lucky). :)

                Luc Pattyn [Forum Guidelines] [My Articles]


                This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


                H 1 Reply Last reply
                0
                • L Luc Pattyn

                  don't set CheckForIllegalCrossThreadCalls false, this is a terrible hack, that WILL result in malfunction, sooner or later (sooner if you are lucky). :)

                  Luc Pattyn [Forum Guidelines] [My Articles]


                  This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


                  H Offline
                  H Offline
                  half life
                  wrote on last edited by
                  #8

                  Bingo, Thanks Luk this is what i intented :):)

                  Have Fun Never forget it

                  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