Force your Thread to start in Single-threaded apartment state

Use the below piece of code if you want to start your thread from main thread passing multiple parameters to that thread:

//by default this thread will start in MTA(Multi Apartment state)
string firstValue;
int secondValue;
bool thridValue;
//create an thread
Thread myAutomationThread;
// The delegate to call.
ThreadStart ts = new ThreadStart(delegate() { callMyFun(firstValue,secondValue,thirdValue); });
// The thread.
myAutomationThread = new Thread(ts);
// Run the thread.
myAutomationThread.Start();
———-
Now if you want to start the same thread in Single apartment state then just add the below line of code.
(We need to start the thread in STA because WATiN will run in STA mode only)

myAutomationThread.SetApartmentState(ApartmentState.STA);

The whole piece of code will look like this:

Thread myAutomationThread;
ThreadStart ts = new ThreadStart(delegate() { callMyFun(firstValue,secondValue,thirdValue); });
myAutomationThread = new Thread(ts);
myAutomationThread.SetApartmentState(ApartmentState.STA);
myAutomationThread.Start();

~Jawed

One thought on “Force your Thread to start in Single-threaded apartment state

  1. this is kinda cooo0ool 🙂

    I'm Rob, im new here! hello

    ___________________________________
    [url=http://www.toniccouture.com]New York Recording Studio[/url] ????

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s