我看到了关于这个话题的一些讨论并得出结论,这是不可能的。我应该使用线程,并将其设置为STA,当我需要返回结果时,使用创建的线程与主线程连接。这可以工作,但不是理想的解决方案,因为使用委托我可以实现纯异步行为(使用回调)。因此,回到起点 - 在我开始实现自己的Future类之前(就像Java中的Future类);是否有更好的方法使用委托来实现这一点?
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
}