Ilya Bezus Ilya Bezus - 2 months ago 16
C# Question

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?

Answer

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 */});
Comments