gpt4 book ai didi

c# - 在异步线程中创建对象会导致 STA 异常

转载 作者:行者123 更新时间:2023-11-30 15:20:42 24 4
gpt4 key购买 nike

我有一个类,当某些操作的状态发生变化时,它应该向用户显示一些消息,如下所示:

public static class AutoUpdater
{
public static async void AutoUpdateCheck()
{
UpdaterStatus.CurrentUpdateStatus = await UpdaterLogic.CheckForUpdateAsync();
}

public static void OnStatusChanged()
{
switch (UpdaterStatus.CurrentStatus)
{
case UpdateStatus.UpdateFound:
{
Message ToAdd = new Message("some params"); //Exception here
MessagesManager.AddNewMessage(ToAdd);
break;
}
//some other cases
}
}

当应用程序启动时,我订阅 AutoUpdater 到这样的事件:

UpdaterStatus.EventStatusChanged += (sender, args) => { AutoUpdater.OnStatusChanged(); };

我得到的异常是:“调用线程必须是 STA,因为许多 UI 组件都需要这个”。

但是,我不能自己创建STA线程,然后将新创建的消息添加到它的父控件中,因为这样我得到一个异常,说“that object belongs to another thread”。

有什么解决方法吗?

最佳答案

您应该从 UI 线程创建 UI 控件。你可以在这里尝试使用dispatcher

Application.Current.Dispatcher.Invoke(/* your action here*/ () => {/* creating UI controls */});

关于c# - 在异步线程中创建对象会导致 STA 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368483/

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