I am calling WatiN from a C# windows service. When I invoke WatiN it throws the following exception. The CurrentThread needs to have it's ApartmentState set to开发者_开发技巧 ApartmentState.STA to be able to automate Internet Explorer
I have tried starting up a thread and setting the apartment state via
mythread.SetApartmentState(ApartmentState.STA)
but that resulted in another error
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I also tried adding an attribute to the Service entry point.
static class Program
{
[STAThread]
static void Main()
{
...
Any ideas?
I know Benjamin's already posted a 'working' answer, but I thought I'd add a couple of things I've experienced when I've got this error when trying to execute WatiN tests: For NUnit, you should add something like this to your app.config for the tests:
<configSections>
<sectionGroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<NUnit>
<TestRunner>
<!-- WatiN can only host IE in STA mode -->
<add key="ApartmentState" value="STA"/>
</TestRunner>
</NUnit>
In MbUnit, modify your TestFixture attribute like this:
[TestFixture(ApartmentState = ApartmentState.STA)]
HTH, Pete.
Ha - it's actually in the documentation. Doh! http://watin.org/documentation/sta-apartmentstate/
That's not an error, it is just a diagnostic from the debugger. It is telling you that it can't give you debug info on whatever you put in the watch window. That's common with code that is compiled in the Release configuration, the JIT compiler optimizes the machine code and commonly puts local variables in CPU registers. Making their value unavailable to the debugger, it isn't smart enough to figure out what register was used. It occasionally happens in the Debug release as well when there's unmanaged code on the call stack. Which is not uncommon for WebBrowser, there's a very large chunk of unmanaged code that makes it work.
FWIW, just switching the thread's apartment state to STA is not enough. The thread must also pump a Windows message loop to make a single-threaded apartment operate properly. If you don't, you'll see that operations on STA objects like WebBrowser will deadlock. For example, you'll never get the DocumentCompleted event when you navigate to a site. Running a message loop requires calling Application.Run() or Form.ShowDialog() in a WF app.
The attribute that I used to get over seeing this error is: [TestFixture, RequiresSTA]
As per adrianbanks answer on: How to run unit tests in STAThread mode?
精彩评论