See the question and my original answer on StackOverflow

You can add this to your usings:

using System.Windows.Threading;

For .NET 5/6, that is enough. For .NET framework you must also add a reference to System.Windows.Presentation.dll.

And this type of code will work fine:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // here we're in UI thread
    var max = 100;
    pg.Maximum = max; // pg is a progress bar
    Task.Run(() =>
    {
        // here we're in another thread
        for (var i = 0; i < max; i++)
        {
            Thread.Sleep(100);

            // this needs the System.Windows.Threading using to support lambda expressions
            Dispatcher.BeginInvoke(() =>
            {
                // this will run in UI thread
                pg.Value = i;
            });
        }
    });
}