Thread State Exception
I am using watin in a class and i am calling that class in background worker Do Work but at the first line it throws exception
The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer.
What can i do?
In one thread at stackoverflow there was a discussion same like t开发者_Go百科his but his issue was solved by something like joining threads.
COM, the grandfather of .NET, does something that .NET doesn't do. You can write a .NET program that use a List<> in a thread and if you don't lock properly it will fail miserably without a diagnostic. COM however is aware of the threading requirements of a COM component. And if the component says it is not thread-safe then you can't ignore that. Which is what the error message means, it can only be used in a 'single-threaded apartment', STA. An STA thread has the plumbing to automatically marshal a call made on the component from a worker thread to the thread that created the component. Quite similar to Control.Invoke(), but done automatically.
That limits your options to use it in a multi-threaded way severely. Other than keeping this running on the UI thread of a GUI app, the only other thing you can do is create an STA thread in which you create both the IE and watin instances. This answer shows you how. Note that BackgroundWorker cannot do this, its DoWork method always runs on an MTA thread. Key parts of the linked code is Thread.SetApartmentState to switch the thread to STA and the message loop started by Application.Run(). Both are required to let these COM components function correctly.
The background worker uses threads from the ThreadPool, which I believe are MTA be default. You should create a new Thread instance and call SetApartmentState(STA) on it.
精彩评论