Ilya Bezus Ilya Bezus - 1 year ago 94
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
//some other cases

When app starts, i subscribe
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 Source

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