Managing Multiple Threads in Managed Code
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 hangs.
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.
The following guidelines use the APIs in the Microsoft.VisualStudio.Threading namespace, in particular, the JoinableTaskFactory class. The APIs in this namespace are new in Visual Studio 2013. You can get an instance of a JoinableTaskFactory from the ThreadHelper property ThreadHelper.JoinableTaskFactory.
If you’re on a background thread and you want to do something on the UI thread, use 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: