gpt4 book ai didi

c# - 如何使委托(delegate)线程成为STA

转载 作者:行者123 更新时间:2023-11-30 15:45:14 25 4
gpt4 key购买 nike

我看到一些围绕这个主题的讨论,并得出结论认为这是不可能的。我应该使用线程,使其成为 STA,当我需要返回结果时,将主线程与创建的线程连接起来。这可以工作,但它不是一个理想的解决方案,因为使用委托(delegate)我可以实现纯异步行为(使用回调)。因此,归一化——就在我开始实现自己的 Future 类之前(如在 Java 中);有没有更好的方法来使用委托(delegate)来实现这一点?


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
}

最佳答案

这是不可能的。委托(delegate)的 BeginInvoke() 方法始终使用线程池线程。并且 TP 线程始终是 MTA,无法更改。要获得 STA 线程,您必须创建一个 Thread 并在启动它之前调用其 SetApartmentState() 方法。该线程还必须提供一个消息循环 Application.Run()。 COM 对象仅在其实例在该线程中创建时使用它。

不确定您要做什么,但是尝试对非线程安全的代码块进行多线程处理是行不通的。 COM 强制执行这一点。

关于c# - 如何使委托(delegate)线程成为STA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5408155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com