Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects inside async thread causes STA exception

I have a class, which should show some messages to the user, when the status of some operation is changed, like this:

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
                }
        }

When app starts, i subscribe AutoUpdater to an event like this:

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

The exception I get is: "The calling thread must be STA, because many UI components require this".

However, I can't create the STA thread by myself, and then add newly created message to its parent control, because this way I get an exception, saying that "that object belongs to another thread".

Is there any workaround?

like image 546
Ilya Bezus Avatar asked Jan 23 '26 20:01

Ilya Bezus


1 Answers

You should to create UI controls from UI thread. You can try to use dispatcher here

Application.Current.Dispatcher.Invoke(/* your action here*/ () => {/* creating UI controls */});
like image 80
tym32167 Avatar answered Jan 25 '26 10:01

tym32167



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!