0

Am new to vb.net multithreading.

Currect me if i'm doing anything wrong.

What i'm trying to do :

user's needs to put the serial no's into textbox then program needs to pick the model and warranty infomation from vendor website when the user hit the search button.

My windows form have two textbox's and two webbrowsers and then one datagridview control.

What i'm trying to do is when the user hit the search buttom the code needs to do below things

Thread1: Pick the serial no from textbox1 and needs to get the information from web using webbrowser1 Thread2:Pick the serial no from textbox2 and needs to get the information from web using webbrowser2

My code looks like

Dim thread1 As System.Threading.Thread
Dim thread2 As System.Threading.Thread

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)          Handles Button1.Click

    thread1 = New System.Threading.Thread(AddressOf thread11)
    thread1.Start()

    thread2 = New System.Threading.Thread(AddressOf thread22)
    thread2.Start()

   End Sub

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles       MyBase.Load
    Me.CheckForIllegalCrossThreadCalls = False
End Sub

 Sub thread11()
 ' Takes the serial no from text1 and searches the information using webbrowser1 goes here
end sub 

Sub thread22()
 ' Takes the serial no from text2 and searches the information using webbrowser2 goes here
  end sub 

But i'm getting the below error messange when i debug the code

An error occurred creating the form. See Exception.InnerException for details. The error is: ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.

it will be great if you tell what i'm doing wrong , what needs to be done and all

Thanks Sathish

Sathish Kothandam
  • 1,530
  • 3
  • 16
  • 34
  • possible duplicate of [Single-threaded apartment - cannot instantiate ActiveX control](http://stackoverflow.com/questions/1418466/single-threaded-apartment-cannot-instantiate-activex-control), also http://stackoverflow.com/questions/7857112/c-sharp-webbrowser-error-thread – stuartd May 09 '13 at 15:55
  • Its typically bad practice to use anything other than the main program thread to interact with UI controls. Try using BackgroundWorker, as it makes this kind of thing safer and less difficult. – StingyJack May 09 '13 at 16:00

1 Answers1

2

When you create your threads, try to set the apartment state.

thread1 = New System.Threading.Thread(AddressOf thread11)
thread1.SetApartmentState(ApartmentState.STA)
thread1.Start()

thread2 = New System.Threading.Thread(AddressOf thread22)
thread2.SetApartmentState(ApartmentState.STA);
thread2.Start()
the_lotus
  • 12,668
  • 3
  • 36
  • 53