Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix the error: "The currentthread needs to have its apartmentstate set to ApartmentState.sta to be able to initiate Internet Explorer"?

Tags:

c#

nunit

watin

I have the following code in C#:

namespace Tests
{    
    [SetUpFixture, RequiresSTA]
    public class Setup
    {
        public IE Window = new IE("webpage");

        [SetUp]
        public void SetUp()
        {

        }

        [TearDown]
        public void TearDown()
        {

        } 
    }
}

When I try to run it with my website it returns the error:

"The currentthread needs to have its apartmentstate set to ApartmentState.sta to be able to initiate Internet Explorer"

Normally when using anything except SetupFixture, RequiresSTA it the solution. But for some reason it is not working now.

like image 434
Emerica. Avatar asked Oct 05 '12 20:10

Emerica.


2 Answers

The solution acctually ended up being rather simple, if you include the line:

[assembly: RequiresSTA] 

at the top of your page it will setup the entire assembly to use STA and it no longer throws the error.

like image 77
Emerica. Avatar answered Nov 03 '22 01:11

Emerica.


You can try starting a new thread and set its ApartmentState:

var t = new Thread(new ThreadStart(ToDo));
t.SetApartmentState(ApartmentState.STA);
t.Start();
// Run synchronously by waiting for t to finish.
t.Join(); 

And the delegate:

private void ToDo()
{
    // Do something...
}

Or inline version:

var t = new Thread(() => 
{
    // Do something...
});
like image 5
Mario S Avatar answered Nov 02 '22 23:11

Mario S