Sunday 26 December 2010

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

1 comment:

Anonymous said...

this is kinda cooo0ool :)

I'm Rob, im new here! hello


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