c# - 如何在 STA 线程中运行某些东西?

标签 c# .net wpf sta

在我的 WPF 应用程序中,我进行了一些异步通信(与服务器)。在回调函数中,我最终根据服务器的结果创建了 InkPresenter 对象。这要求正在运行的线程是 STA,而目前显然不是。因此我得到以下异常:

Cannot create instance of 'InkPresenter' defined in assembly [..] The calling thread must be STA, because many UI components require this.

目前我的异步函数调用是这样的:

public void SearchForFooAsync(string searchString)
{
    var caller = new Func<string, Foo>(_patientProxy.SearchForFoo);
    caller.BeginInvoke(searchString, new AsyncCallback(SearchForFooCallbackMethod), null);
}

如何使回调(将创建 InkPresenter)成为 STA?或者在新的 STA 线程中调用 XamlReader 解析。

public void SearchForFooCallbackMethod(IAsyncResult ar)
{
    var foo = GetFooFromAsyncResult(ar); 
    var inkPresenter = XamlReader.Parse(foo.Xaml) as InkPresenter; // <!-- Requires STA
    [..]
}

最佳答案

您可以像这样启动 STA 线程:

    Thread thread = new Thread(MethodWhichRequiresSTA);
    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
    thread.Start(); 
    thread.Join(); //Wait for the thread to end

唯一的问题是您的结果对象必须以某种方式传递。您可以为此使用私有(private)字段,或者深入研究将参数传递到线程中。在这里,我将 foo 数据设置在一个私有(private)字段中,并启动 STA 线程来改变 inkpresenter!

private var foo;
public void SearchForFooCallbackMethod(IAsyncResult ar)
{
    foo = GetFooFromAsyncResult(ar); 
    Thread thread = new Thread(ProcessInkPresenter);
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join(); 
}

private void ProcessInkPresenter()
{
    var inkPresenter = XamlReader.Parse(foo.Xaml) as InkPresenter;
}

希望这对您有所帮助!

关于c# - 如何在 STA 线程中运行某些东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2378016/

相关文章:

c# - 如何解决调用 Amazon SP-API 的问题,即使使用有效的 token 和签名,它也始终返回未经授权

c# - Winforms用户控件现象: suddenly all items are away!

c# - CheckBox 模板中的选中状态未更新

c# - IP 地址的正则表达式

C# WPF ComboBox 鼠标悬停在颜色上

c# - WPF 设置窗口数据上下文

c# - 在 appSettings 中存储值

c# - Silverlight:是否可以在文本框中对 XML 进行语法着色?

c# - 如果条件= true,则用链接包装内容?

c# - 在异步方法 .net 4.5 中管理同步调用