开发者

WatIn multithreading

开发者 https://www.devze.com 2023-02-20 13:59 出处:网络
How can I work with WatIn using async delegates? I tried, but it returned this error: The CurrentThread needs to have it\'s ApartmentState set to

How can I work with WatIn using async delegates? I tried, but it returned this error:

The CurrentThread needs to have it's ApartmentState set to Apart开发者_高级运维mentState.STA to be able to automate Internet Explorer.


I assume you use BeginInvoke() on your delegates. They use the thread pool to do threaded work and the threads in the thread pool are all MTA's. You will have to do it the old fashion way by creating your own Thread. The thread class offers methods (GetApartmentState and SetApartmentState) to change the apartment model.

I guess you might need your own message pump as well in your thread.

Something like this might get you started:

var th = new Thread(() => { /* do work */ });
th.SetApartmentState(ApartmentState.STA);
th.Start();


Because of the nature of how the IE COM interop works, it inherently needs to be run in a single-threaded apartment. The following is copied from the [watin.org] page on the subject1

Why is setting the ApartmentState needed in the first place?

Copied from MSDN:

“Because COM classes use apartments, the common language runtime needs to create and initialize an apartment when calling a COM object in a COM interop situation. A managed thread can create and enter a single-threaded apartment (STA) that allows only one thread, or a multithreaded apartment (MTA) that contains one or more threads.”.

Since Internet Explorer is not Thread safe we need to use STA.

Implications

Using WatiN works fine in a console or GUI application when you apply the [STAThread] attribute to the main method (the sole entry point of the application). This way the main Thread runs as STA and all goes well. When using a runner like MBUnit, NUnit or any other runner that starts the main Thread, your code/tests depend upon the ApartmentState the runner started with.

Behaviour of WatiN when Thread is not an STA Thread.

WatiN will throw a ThreadStateException when you create an instance of the WatiN.Core.IE class, to help you remind to set the ApartmentState to STA.


Use RequiresSTA attribute, starting with NUnit 2.5.

EDIT

Use Apartment attribute, starting with NUnit 3.0.

0

精彩评论

暂无评论...
验证码 换一张
取 消