I have see some discussion around this topic and concluded that it is not possible. I should use Threads, make it STA and when I need result back, join main thread with the created thread. This can work but it is not an ideal solution as using delegates I can achieve pure asynchronous behavior (using callback). So, to square one - just before I start implementing my own Future class (as in Java); Is there a better way to achieve this using delegates?
private delegate String DelegateFoo(String[] input);
private String Foo(String[] input){
// do something with input
// this code need to be STA
// below code throws exception .. that operation is invalid
// Thread.CurrentThread.SetApartmentState(ApartmentState.STA)
return "result";
}
private void callBackFoo(IAsyncResult iar){
AsyncResult result = (AsyncResult)iar;
DelegateFoo del = (DelegateFoo)result.AsyncDelegate;
String result = null;
try{
result = del.EndInvoke(iar);
}catch(Exception e){
return;
}
DelegateAfterFooCallBack callbackDel = new DelegateAfterFooCallBack (AfterFooCallBack);
// call code which should execute in the main UI thread.
if (someUIControl.InvokeRequired)
{ // execute on the main thread.
callbackDel.Invoke();
}
else
{
AfterFooCallBack();
}
}
private void AfterFooCallBack(){
// should execute in main UI thread to update state, controls and stuff
}