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. Illegal cross thread exception in Invoke method

Illegal cross thread exception in Invoke method

Scheduled Pinned Locked Moved C#
csharphelptutorialquestion
18 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.
  • Y yeah1000

    Hello, i am using visual C# express 2008. I SOMETIMES get the illegal cross thread operation in my invoke method when i try to run my project. I check the InvokeRequired property, invoke the same method and in the 'else' condition i create atemporary variable and assign it the text of my control. But on that line, in the 'else' statement, inside the Invoking method i sometimes get the exception. What could be the cause? How to get rid of it? It does not occur often, but it is still a bug... TY

    A Offline
    A Offline
    Abhinav S
    wrote on last edited by
    #2

    Try using BeginInvoke on your control instead.

    Me, I'm dishonest. And a dishonest man you can always trust to be dishonest.
    Honestly. It's the honest ones you want to watch out for...

    A 1 Reply Last reply
    0
    • Y yeah1000

      Hello, i am using visual C# express 2008. I SOMETIMES get the illegal cross thread operation in my invoke method when i try to run my project. I check the InvokeRequired property, invoke the same method and in the 'else' condition i create atemporary variable and assign it the text of my control. But on that line, in the 'else' statement, inside the Invoking method i sometimes get the exception. What could be the cause? How to get rid of it? It does not occur often, but it is still a bug... TY

      D Offline
      D Offline
      Dave Kreskowiak
      wrote on last edited by
      #3

      Without seeing your code, it's pretty much impossible to tell you where it's going wrong.

      A guide to posting questions on CodeProject[^]
      Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
           2006, 2007, 2008
      But no longer in 2009...

      Y 1 Reply Last reply
      0
      • D Dave Kreskowiak

        Without seeing your code, it's pretty much impossible to tell you where it's going wrong.

        A guide to posting questions on CodeProject[^]
        Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
             2006, 2007, 2008
        But no longer in 2009...

        Y Offline
        Y Offline
        yeah1000
        wrote on last edited by
        #4

        Code is the following:

        Delegate:
        private delegate void ChangeTextDelegate(string text);

        Method:
        public static void ChangeText(string text)
        {
        if (richtextbox1.InvokeRequired)
        {
        richtextbox1.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
        }
        else
        {
        int startIndex;
        startIndex = richtextbox1.TextLength; <- Exception points here
        ...
        }
        }

        I call it like this: ChangeText("hello"); (in another thread)

        modified on Thursday, March 18, 2010 7:19 AM

        L A 2 Replies Last reply
        0
        • Y yeah1000

          Code is the following:

          Delegate:
          private delegate void ChangeTextDelegate(string text);

          Method:
          public static void ChangeText(string text)
          {
          if (richtextbox1.InvokeRequired)
          {
          richtextbox1.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
          }
          else
          {
          int startIndex;
          startIndex = richtextbox1.TextLength; <- Exception points here
          ...
          }
          }

          I call it like this: ChangeText("hello"); (in another thread)

          modified on Thursday, March 18, 2010 7:19 AM

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

          Hi, please show code inside PRE tags, that results in better readability. What you have shown seems correct, assuming the RTB got created on the GUI thread. It would be wrong when created e.g. inside the DoWork handler of a BackgroundWorker. How and where did you create it? :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


          I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


          1 Reply Last reply
          0
          • Y yeah1000

            Code is the following:

            Delegate:
            private delegate void ChangeTextDelegate(string text);

            Method:
            public static void ChangeText(string text)
            {
            if (richtextbox1.InvokeRequired)
            {
            richtextbox1.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
            }
            else
            {
            int startIndex;
            startIndex = richtextbox1.TextLength; <- Exception points here
            ...
            }
            }

            I call it like this: ChangeText("hello"); (in another thread)

            modified on Thursday, March 18, 2010 7:19 AM

            A Offline
            A Offline
            AspDotNetDev
            wrote on last edited by
            #6

            FYI, this is what code looks like when you wrap it in PRE tags and specify C# for the LANG attribute, as Luc mentioned:

            // Delegate:
            private delegate void ChangeTextDelegate(string text);

            // Method:
            public static void ChangeText(string text)
            {
            if (richtextbox1.InvokeRequired)
            {
            richtextbox1.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
            }
            else
            {
            int startIndex;
            startIndex = richtextbox1.TextLength; // <- Exception points here.
            // ...
            }
            }

            Not sure why you are getting an exception there (perhaps post a screenshot and the full text of the exception?), but you might try the following to see if it works (changes in bold):

            // Delegate:
            private delegate void ChangeTextDelegate(string text);

            // Method:
            public static void ChangeText(string text)
            {
            if (this.InvokeRequired)
            {
            this.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
            }
            else
            {
            int startIndex;
            startIndex = richtextbox1.TextLength; // <- Exception points here.
            // ...
            }
            }

            FYI, here is what I typed to make the code look like it does above:

            <pre lang="C#">// Delegate:
            private delegate void ChangeTextDelegate(string text);

            // Method:
            public static void ChangeText(string text)
            {
            if (<b><big><big><u>this</u></big></big></b>.InvokeRequired)
            {
            <b><big><big><u>this</u></big></big></b>.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
            }
            else
            {
            int startIndex;
            startIndex = richtextbox1.TextLength; // <- Exception points here.
            // ...
            }
            }</pre>

            [Forum Guidelines]

            Y 2 Replies Last reply
            0
            • A Abhinav S

              Try using BeginInvoke on your control instead.

              Me, I'm dishonest. And a dishonest man you can always trust to be dishonest.
              Honestly. It's the honest ones you want to watch out for...

              A Offline
              A Offline
              AspDotNetDev
              wrote on last edited by
              #7

              FYI, that would prevent a locking situation, but would not likely prevent a cross-thread exception. It would also change the flow of the program (i.e., the call would be asynchronous rather than blocking), which the OP may not want.

              [Forum Guidelines]

              L 1 Reply Last reply
              0
              • A AspDotNetDev

                FYI, that would prevent a locking situation, but would not likely prevent a cross-thread exception. It would also change the flow of the program (i.e., the call would be asynchronous rather than blocking), which the OP may not want.

                [Forum Guidelines]

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

                I agree. :)

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


                1 Reply Last reply
                0
                • A AspDotNetDev

                  FYI, this is what code looks like when you wrap it in PRE tags and specify C# for the LANG attribute, as Luc mentioned:

                  // Delegate:
                  private delegate void ChangeTextDelegate(string text);

                  // Method:
                  public static void ChangeText(string text)
                  {
                  if (richtextbox1.InvokeRequired)
                  {
                  richtextbox1.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
                  }
                  else
                  {
                  int startIndex;
                  startIndex = richtextbox1.TextLength; // <- Exception points here.
                  // ...
                  }
                  }

                  Not sure why you are getting an exception there (perhaps post a screenshot and the full text of the exception?), but you might try the following to see if it works (changes in bold):

                  // Delegate:
                  private delegate void ChangeTextDelegate(string text);

                  // Method:
                  public static void ChangeText(string text)
                  {
                  if (this.InvokeRequired)
                  {
                  this.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
                  }
                  else
                  {
                  int startIndex;
                  startIndex = richtextbox1.TextLength; // <- Exception points here.
                  // ...
                  }
                  }

                  FYI, here is what I typed to make the code look like it does above:

                  <pre lang="C#">// Delegate:
                  private delegate void ChangeTextDelegate(string text);

                  // Method:
                  public static void ChangeText(string text)
                  {
                  if (<b><big><big><u>this</u></big></big></b>.InvokeRequired)
                  {
                  <b><big><big><u>this</u></big></big></b>.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
                  }
                  else
                  {
                  int startIndex;
                  startIndex = richtextbox1.TextLength; // <- Exception points here.
                  // ...
                  }
                  }</pre>

                  [Forum Guidelines]

                  Y Offline
                  Y Offline
                  yeah1000
                  wrote on last edited by
                  #9

                  Here is the stack trace, perhaps it can help clarify the problem...

                  System.InvalidOperationException was unhandled
                  Message="Cross-thread operation not valid: Control 'SomeClass' accessed from a thread other than the thread it was created on."
                  Source="System.Windows.Forms"
                  StackTrace:
                  at System.Windows.Forms.Control.get_Handle()
                  at System.Windows.Forms.Control.get_InternalHandle()
                  at System.Windows.Forms.Control.WmWindowPosChanged(Message& m)
                  at System.Windows.Forms.Control.WndProc(Message& m)
                  at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
                  at System.Windows.Forms.RichTextBox.WndProc(Message& m)
                  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                  at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
                  at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
                  at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
                  at System.Windows.Forms.Control.DefWndProc(Message& m)
                  at System.Windows.Forms.Control.WmCreate(Message& m)
                  at System.Windows.Forms.Control.WndProc(Message& m)
                  at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
                  at System.Windows.Forms.RichTextBox.WndProc(Message& m)
                  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                  at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
                  at System.Windows.Forms.UnsafeNativeMethods.IntCreateWindowEx(Int32 dwExStyle, String lpszClassName, String lpszWindowName, Int32 style, Int32 x, Int32 y, Int32 width, Int32 height, HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, Object pvParam)
                  at System.Windows.Forms.UnsafeNativeMethods.CreateWindowEx(Int32 dwExStyle, String lpszClassName, String lpszWindowName, Int32 style, Int32 x, Int32 y, Int32 width, Int32 height, HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, Object pvParam)
                  at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
                  at System.Windows.Forms.Control.CreateHandle()
                  at System.Windows.Forms.TextBoxBase.CreateHandle()
                  at System.Windows.Forms.Control.get_Handle()
                  at System.Windows.Forms.Ric

                  1 Reply Last reply
                  0
                  • A AspDotNetDev

                    FYI, this is what code looks like when you wrap it in PRE tags and specify C# for the LANG attribute, as Luc mentioned:

                    // Delegate:
                    private delegate void ChangeTextDelegate(string text);

                    // Method:
                    public static void ChangeText(string text)
                    {
                    if (richtextbox1.InvokeRequired)
                    {
                    richtextbox1.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
                    }
                    else
                    {
                    int startIndex;
                    startIndex = richtextbox1.TextLength; // <- Exception points here.
                    // ...
                    }
                    }

                    Not sure why you are getting an exception there (perhaps post a screenshot and the full text of the exception?), but you might try the following to see if it works (changes in bold):

                    // Delegate:
                    private delegate void ChangeTextDelegate(string text);

                    // Method:
                    public static void ChangeText(string text)
                    {
                    if (this.InvokeRequired)
                    {
                    this.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
                    }
                    else
                    {
                    int startIndex;
                    startIndex = richtextbox1.TextLength; // <- Exception points here.
                    // ...
                    }
                    }

                    FYI, here is what I typed to make the code look like it does above:

                    <pre lang="C#">// Delegate:
                    private delegate void ChangeTextDelegate(string text);

                    // Method:
                    public static void ChangeText(string text)
                    {
                    if (<b><big><big><u>this</u></big></big></b>.InvokeRequired)
                    {
                    <b><big><big><u>this</u></big></big></b>.Invoke(new ChangeTextDelegate(ChangeText), new object[] { text });
                    }
                    else
                    {
                    int startIndex;
                    startIndex = richtextbox1.TextLength; // <- Exception points here.
                    // ...
                    }
                    }</pre>

                    [Forum Guidelines]

                    Y Offline
                    Y Offline
                    yeah1000
                    wrote on last edited by
                    #10

                    Soo, any ideas? :)

                    A 1 Reply Last reply
                    0
                    • Y yeah1000

                      Soo, any ideas? :)

                      A Offline
                      A Offline
                      AspDotNetDev
                      wrote on last edited by
                      #11

                      I assume you already tried using the "this" keyword like I said above? If that doesn't work, you can take two approaches. With one approach, try to create the error with a very small tester form. Then, post that here for us to review. Or, try removing code from your project little by little until it starts working.

                      [Forum Guidelines]

                      Y 1 Reply Last reply
                      0
                      • A AspDotNetDev

                        I assume you already tried using the "this" keyword like I said above? If that doesn't work, you can take two approaches. With one approach, try to create the error with a very small tester form. Then, post that here for us to review. Or, try removing code from your project little by little until it starts working.

                        [Forum Guidelines]

                        Y Offline
                        Y Offline
                        yeah1000
                        wrote on last edited by
                        #12

                        I am currently testing it with the 'this' keyword. But why should this approach solve the problem? What are the technicalities behind it? :)

                        A 1 Reply Last reply
                        0
                        • Y yeah1000

                          I am currently testing it with the 'this' keyword. But why should this approach solve the problem? What are the technicalities behind it? :)

                          A Offline
                          A Offline
                          AspDotNetDev
                          wrote on last edited by
                          #13

                          Was just a wild guess really. Not sure if it would help.

                          [Forum Guidelines]

                          Y 1 Reply Last reply
                          0
                          • A AspDotNetDev

                            Was just a wild guess really. Not sure if it would help.

                            [Forum Guidelines]

                            Y Offline
                            Y Offline
                            yeah1000
                            wrote on last edited by
                            #14

                            Okay, that didn't help :( Any more ideas?

                            A 1 Reply Last reply
                            0
                            • Y yeah1000

                              Okay, that didn't help :( Any more ideas?

                              A Offline
                              A Offline
                              AspDotNetDev
                              wrote on last edited by
                              #15

                              Show me the exact code that causes the problem. Create as small of a tester application as you can and paste ALL of the code for it (but remember to try and make the example concise). It's probably something simple, but I can't help you unless I see the code you are using.

                              [Forum Guidelines]

                              Y 1 Reply Last reply
                              0
                              • A AspDotNetDev

                                Show me the exact code that causes the problem. Create as small of a tester application as you can and paste ALL of the code for it (but remember to try and make the example concise). It's probably something simple, but I can't help you unless I see the code you are using.

                                [Forum Guidelines]

                                Y Offline
                                Y Offline
                                yeah1000
                                wrote on last edited by
                                #16

                                I was finally able to fix the problem: Apparently the handle for the richtextbox did not exist when i tried to invoke it. Since i used it in a background thread, the invokerequired property returned 'false', sometimes causing it to display the illegal cross thread operation exception (suring program startup). The solution was to use the Form_load event which would signal the background thread when it was fully loaded. But its still a bit unclear how such a thing can happen. When does actually InitializeComponent return? When can i be sure that the control handles exist?

                                A 1 Reply Last reply
                                0
                                • Y yeah1000

                                  I was finally able to fix the problem: Apparently the handle for the richtextbox did not exist when i tried to invoke it. Since i used it in a background thread, the invokerequired property returned 'false', sometimes causing it to display the illegal cross thread operation exception (suring program startup). The solution was to use the Form_load event which would signal the background thread when it was fully loaded. But its still a bit unclear how such a thing can happen. When does actually InitializeComponent return? When can i be sure that the control handles exist?

                                  A Offline
                                  A Offline
                                  AspDotNetDev
                                  wrote on last edited by
                                  #17

                                  Glad to hear you got it working. :) InitializeComponent should be called from the constructor. You should only reference controls after that call to InitializeComponent.

                                  [Forum Guidelines]

                                  Y 1 Reply Last reply
                                  0
                                  • A AspDotNetDev

                                    Glad to hear you got it working. :) InitializeComponent should be called from the constructor. You should only reference controls after that call to InitializeComponent.

                                    [Forum Guidelines]

                                    Y Offline
                                    Y Offline
                                    yeah1000
                                    wrote on last edited by
                                    #18

                                    Oh but i did call it from the constructor, then started the background thread and inside that thread tried to access the controls.

                                    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