If you have a managed VSPackage extension that calls asynchronous methods or has operations that execute on threads other than the Visual Studio UI thread, you should follow the guidelines given below. You can keep the UI thread responsive because it doesn't need to wait for work on another thread to complete. You can make your code more efficient, because you don't have extra threads that take up stack space, and you can make it more reliable and easier to debug because you avoid deadlocks and unresponsive code.
In general, you can switch from the UI thread to a different thread, or vice versa. When the method returns, the current thread is the thread from which it was originally called.
If you are on the UI thread and you want to do asynchronous work on a background thread, use Task.Run():
C#
await Task.Run(asyncdelegate{
// Now you're on a separate thread.
});
// Now you're back on the UI thread.
If you are on the UI thread and you want to synchronously block while you are performing work on a background thread, use the TaskScheduler property TaskScheduler.Default inside Run:
C#
// using Microsoft.VisualStudio.Threading;
ThreadHelper.JoinableTaskFactory.Run(asyncdelegate {
await TaskScheduler.Default;
// You're now on a separate thread.
DoSomethingSynchronous();
await OrSomethingAsynchronous();
});
Switch from a background thread to the UI thread
If you're on a background thread and you want to do something on the UI thread, use SwitchToMainThreadAsync:
C#
// Switch to main threadawait ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
You can use the SwitchToMainThreadAsync method to switch to the UI thread. This method posts a message to the UI thread with the continuation of the current asynchronous method, and also communicates with the rest of the threading framework to set the correct priority and avoid deadlocks.
If your background thread method isn't asynchronous and you can't make it asynchronous, you can still use the await syntax to switch to the UI thread by wrapping your work with Run, as in this example:
C#
ThreadHelper.JoinableTaskFactory.Run(asyncdelegate {
// Switch to main threadawait ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Do your work on the main thread here.
});
Learn how to efficiently debug your .NET app by using Visual Studio to fix your bugs quickly. Use the interactive debugger within Visual Studio to analyze and fix your C# applications.