views:

487

answers:

2

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?
+2  A: 

You could lower the priority of your background thread, so it will be preempted more by the OS. If you have some domain knowledge that leads you to want to control when it's preempted, you could go with Thread.Sleep(0) which surrender your timeslice if there's another thread waiting.

Application.DoEvents pumps the windows message queue. This will cause your app to respond to events like keystrokes or window resizes. Thread.Sleep will cause your thread to be preempted (or maybe not, in the case of Thread.Sleep(0)).

Also read Threading in C#

aumfer
A: 

The proper way to do this is by using callbacks, though. See the Silverlight model of using Asynchronous methods (for retrieving web service data, for example). I know this question is "answered" but the answer is not ideal IMHO.

Wade