gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:59:49 26 4
gpt4 key购买 nike

在我的 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/

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