-3

I'm using WatiN to login a website. WatiN requires STAThread attribute to be applied on the thread that will be running on. Until now all things were good but now I have a long-task. I'm using WPF and need to keep UI responsive. So I have tried something like this:

_downloadTask = new Task(StartDownload, _cancelationToken.Token);

[STAThread]
public override void StartDownload()
{
    if(IsLoginNeeded)
    {
       bool result = Login();
       // check the result and do some other work..
    }
}

[STAThread]
public bool Login()
{
     if (_browser == null)
           _browser = new IE(LoginUrl); // exception

}

When I started my Task, I get ThreadStateException on new IE(LoginUrl) :

The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer.

As you can see I have tried to apply STAThread on my methods but I couldn't succeeded.Now I'm wondering if it's possible to apply STAThread attribute to a thread that is created on runtime or is there another way to do this?

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • 1
    @Servy has a nice Task wrapper around the `Thread` class [here](http://stackoverflow.com/questions/16720496/set-apartmentstate-on-a-task) – Yuval Itzchakov Jul 13 '14 at 23:07
  • 1
    You can also use my [`MessageLoopApartment`](http://stackoverflow.com/a/21808747/1768303), it provides familiar `Task Run(Action)` and `Task Run(Func>)` wrappers. – noseratio Jul 13 '14 at 23:24

1 Answers1

1
Thread t = new Thread(() =>
{
    StartDownload();
    Application.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
I4V
  • 34,891
  • 6
  • 67
  • 79