0

I have written an application which does lots of calculation on huge floating point numbers that makes the UI not responsive at all most of the time.

I am thinking of adding a status bar to this application and show some info about cpu load, used memory and a progress bar. Consider adding labels and progress bar to the statusbar as childs, how can I run this status bar on a separate thread which can be reliable to be responsive as much as possible?

I can already use progress bars and system diagnosting stuff normally. What I am looking for is your ideas and tips, possibly with some codes!

Update

I want the status bar shows real time cpu and memory details. How to workaround this?

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 1
    I'm pretty sure your huge calculations are the ones to be run in a background worker thread not your UI updates. – omarello Dec 19 '11 at 08:54
  • Fix the cause rather than the symptoms: run the computation using a backgroundworker. – Mitch Wheat Dec 19 '11 at 08:59
  • You can't. All UI controls have to run on a single thread, called the UI thread. As the others have suggested, using a `BackgroundWorker` component *for the calculation* is the correct approach. The MSDN documentation has an excellent example. – Cody Gray - on strike Dec 19 '11 at 09:52
  • So how can I do something that cpu usage and memory avilable be showed in real time?! Only thing I can think is put them in a loop but what will happen to the rest of UI ? – Dumbo Dec 19 '11 at 10:09
  • Use a timer for the regular updates – David Heffernan Dec 19 '11 at 10:12
  • There's no such thing as "real time" in a Windows OS. You can use another backgroundworker and Performance counters (see http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c) to get the CPU and memory values, then regularly update the UI by firing events – Strillo Dec 19 '11 at 10:14
  • Does timer cause UI to be unresponsive when it ticks and events should be done in the tick time are processing?! – Dumbo Dec 19 '11 at 10:14

2 Answers2

3

You've got this the wrong way round. You should run all the UI in the same thread, and run the long calculation in a background worker. Trying to run UI in different threads within the same app just leads to pain.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thanks, but what I ment is that I want status bar show real time cpu and memory usage no matter what is going on in other places in the application. is this also follows the same rule you said? – Dumbo Dec 19 '11 at 10:11
  • Yes. Just run a timer to provoke regular updates and keep all UI in the main thread. Run long calcs on worker threads away from UI thread. – David Heffernan Dec 19 '11 at 10:19
2

Best thing is to just do a google search on BackgroundWorker. Here is one particular result on how to use it.

http://midnightprogrammer.net/post/Using-Background-Worker-in-C.aspx

omarello
  • 2,683
  • 1
  • 23
  • 23