How to resolve VS2019 warning to use `JoinableTaskFactory.SwitchToMainThreadAsync()` instead of Invoke / BeginInvoke?

Viewed 1692

If I use

Application.Current.Dispatcher.BeginInvoke(new Action(() => { /*UI code here*/ }));

in a WPF project, Visual Studio 2019 gives me warning VSTHRD001:

Await JoinableTaskFactory.SwitchToMainThreadAsync() to switch to the UI thread instead of APIs that can deadlock or require specifying a priority.

How do I implement this suggestion?

1 Answers

Look here. You should replace the call to BeginInvoke with this:

Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.Run(async delegate {
    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
    /*UI code here*/
});
Related