1

I am using Watin inside Task which throw exception

ThreadStateException with an error message of 'The CurrentThread needs to have its ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer'

My code is look like

 Task task = Task.Factory.StartNew(() =>
                    {
              try{
                     string  Url="www.google.com";
                     IE ie = new IE(Url);
                }
               catch (Exception ex)
             {
             throw ex; //ThreadStateException 
             }    
});

How can i solve this problem?
I am trying to google but unable to find solution.

Aamir
  • 345
  • 4
  • 24
  • If you care about what kind of thread the task needs to run on, maybe you should just be creating a thread instead. You can wrap it in a method that uses `TaskCompletionSource` to expose a `Task`. See http://stackoverflow.com/a/16722767/1726343 – Asad Saeeduddin Jul 27 '15 at 18:25

2 Answers2

1

Nothing "wrong" with the code. Read this on the WatIn documentation:

http://watin.org/documentation/sta-apartmentstate/

From the documentation:

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.

ProgrammerV5
  • 1,915
  • 2
  • 12
  • 22
-1

Use async method with wait. You can get lots of examples for that from web.