Thread operation not valid

I see the following in the output

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>PremiumCharger.vshost.exe</AppDomain><Exception><ExceptionType>System.InvalidOperationException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Cross-thread operation not valid: Control 'textboxRequest' accessed from a thread other than the thread it was created on.</Message><StackTrace>   at System.Windows.Forms.Control.get_Handle()
   at System.Windows.Forms.Control.set_WindowText(String value)
...........

 

Excerpts from my code:

class Form1
{
...
                    processor1.AfterProcessing += new Processor.AfterProcessingHandler(processor1_AfterProcessing);
...
       private void processor1_AfterProcessing(string request, string response)
        {
            textboxRequest.Text = request;
            textboxResponse.Text = response;
        }
...
}

class Processor
{
            backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
...
// Timer calls backgroundWorker1.DoWork()
...
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            OnAfterProcessing(stringRequest, stringResponse);
        }

        public delegate void AfterProcessingHandler(string request, string response);
        public event AfterProcessingHandler AfterProcessing;

        protected void OnAfterProcessing(string request, string response)
        {
            if (AfterProcessing != null)
            {
                if (request != null && response != null)
                {
                    AfterProcessing(request, response);
                }
            }
        }
...
}

 

Can anyone make heads or tails on this error and how to resolve it



Answer this question

Thread operation not valid

  • big71

    Invoke exists on the Control class, so you need the form or control instance.< xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

     

    -mark

    Program Manager

    Microsoft

    This post is provided "as-is"

     


  • ashish_2060

    It looks like you are accessing a control on a non-UI thread. See the details of the exception: Cross-thread operation not valid: Control 'textboxRequest' accessed from a thread other than the thread it was created on.

     

    You cannot do anything that affects the UI in the DoWork method.

    < xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> 

    -mark

    Program Manager

    Microsoft

    This post is provided "as-is"

     


  • S&amp;#246;nmez

    Did you notice the error message ie
    Cross-thread operation not valid: Control 'textboxRequest' accessed from a thread other than the thread it was created on.

    private void processor1_AfterProcessing(string request, string response)
    {
                textboxRequest.Text = request;
                textboxResponse.Text = response;
    }

    processor1_AfterProcessing is being called from a Thread which textboxRequest was not created on. You need to use Invoke( ) to Marshall the call to your Form1 class.

    Look at
    http://www.devsource.com/article2/0,1895,1893360,00.asp

    This *will* fix your problem.

    Wal

  • http200

    DoWork doesn't call OnAfterProcessing, rather only backgroundWorker1.RunWorkerCompleted handler does.

    I thought RunWorkerCompleted automatically mashalled to Form1.

    Could it be because the background thread is called by the Timer thread   But the timer1_Elapsed operates in the UI thread, right

    Thanks for the quick responses.  I'll add Invoke and report back.


  • Igor Tur

    I can't figure out how to use Invoke.  In the article, Invoke takes the form:

            void worker_DoWork(object sender, DoWorkEventArgs e)
            {
                for (int i = 0; i < (int)e.Argument; i++)
                {
                    if (InvokeRequired)
                        Invoke(new Change(OnChange), i);
                }
            }

            private void OnChange(int i)
            {
                textBox1.Text += i.ToString() + ",";
                Application.DoEvents();
            }

            private delegate void Change(int i);

    But, in mine, updating the DoWork event with

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
                    if (InvokeRequired)
                        Invoke(new AfterProcessingHandler(OnAfterProcessing), stringRequest, stringResponse);
    }

    gives me an error "InvokeRequired does not exist in the current context."

    Do I need to place InvokeRequired / Invoke in class Form1   If so, how do I invoke OnAfterProcessing which is in class Processor


  • Roil_O

    The easiest way to find out re: marshalling is to ask.

    private void processor1_AfterProcessing(string request, string response)
            {
                Console.WriteLine(this.InvokeRequired);
                //don't do the below if required, invoke
                textboxRequest.Text = request;
                textboxResponse.Text = response;
            }



  • giantpanda77

    I was using System.Timers.Timer rather than System.Windows.Forms.Timer

    Per http://msdn.microsoft.com/msdnmag/issues/04/02/TimersinNET/

    "... the System.Timers.Timer class members are very similar to those of the System.Windows.Forms.Timer class. The biggest difference is that System.Timers.Timer is a wrapper around Win32 waitable timer objects and raises an Elapsed event on a worker thread rather than a Tick event on the UI thread."


  • Thread operation not valid