tags:

views:

1317

answers:

1

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?

+1  A: 

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.

WFIW, 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.

Hans Passant
That makes a great deal of sense!
Jonathan
Thanks very much. Joining the thread helped resolve the issue!
Jonathan