We have a desktop application that performs a pretty rigorous set of calculations in a background thread. Portions of this calculation are performed in an unmanaged library that we access through interop. What we are finding is that, when we kick off the calculation, the UI thread becomes unresponsive for the duration of the calculation. We were under the impression that the framework would handle the thread switching to permit the UI to continue to be responsive, but that is not the case. We have found that we can insert a Thread.Sleep(0) or Application.DoEvents() to permit the UI to be responsive. This has the side effect of slowing the calculation. Also, portions of the calculation performed by the unmanaged code can take up to 30 seconds to complete, and during this time the application is always unresponsive. The entire calculation can take anywhere from two to five minutes to complete.
This leads to the following questions:
- What is the .NET framework threading model with regard to the UI and interop?
- Are we incorrect in assuming that the framework should handle thread switching between the background and UI threads?
- What is the difference between using Thread.Sleep and Application.DoEvents in this situation, and is one preferred over the other?