-1

An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll webbrowser control

I am trying to capture the frames of a video and then processing them in a separate thread. After processing the frame I need to call a form that has a webBrowser control in for displaying the web page as an over lay on first winform.

Is there any way out that I can call this form inside the class I am using for processing the frames. If I do i keep getting haunted by the above specified exception.

I have done research on SO and other forums but could not get any solution for this issue. Here is my code:

  class FrameProcessor
        {
//This line results in the above stated Exception.
webForm frm=new webForm ();
frm.Show();
 }

Is there any work around for this? Any suggestions would be really appreciated.

G droid
  • 956
  • 5
  • 13
  • 36
  • _"I have done research on SO and other forums but could not get any solution"_ - Golly look what I found in the right hand margin. _[Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the?rq=1)_ –  Sep 12 '15 at 13:50

2 Answers2

2

You can only create/invoke UI code (code that will render on the screen) with a UI thread. So you would need to "invoke" this code on the UI thread.

Your thread needs a reference to some winform or control, you could create a method, for example.

You add this to your "first winform" (as you referred to it in your question).

public void Launch(){
  Invoke((MethodInvoker) delegate {
    webForm frm=new webForm ();
    frm.Show();
   });
}

Now as long as your non UI thread has access to the winform that has the above method you can call it.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • 1
    Though a jolly good answer, `BeginInvoke()` is arguably better –  Sep 12 '15 at 13:51
  • @T McKeown: It would be really great if you could demonstrate me how can I call this method in non-UI thread. – G droid Sep 14 '15 at 06:23
0

In my case this was the solution:

if (Application.OpenForms.OfType<webForm>().Count() == 0)
                      ().First().Show();
                    {
                     webForm frm = new webForm();
                     frm.Show();
                     }

                    Application.Run();
                }
                else
                {
                    if (Application.OpenForms.OfType<webForm>().Count() == 1)
                    {
                        Form fc = Application.OpenForms["webForm"];

                        if (fc != null)
                            fc.Invoke(new MethodInvoker(delegate { fc.Close(); }));


         }
G droid
  • 956
  • 5
  • 13
  • 36