views:

53

answers:

3

I am new to the world of GUI programming and I am writing a little GUI app using IronPython and WinForms. It reads values from an external device and displays them in a ListView component (name, value). I want to periodically perform the reading and updating of the ListView component at a certain fixed rate.

I had the following ideas to accomplish this:

  • A timer, which periodically triggers the read/screen update directly in the OnTick handler
  • A timer, whose OnTick handler triggers a BackgroundWorker to perform the read/update

Since the first solution will block the GUI until the read/update loop is done, which, depending on the number of values being read from the device, could take some time, I think the BackgroundWorker might be a better solution. I might want to add some functionality to manipulate the ListView items later (add, remove values etc.) and a blocked GUI does not seem like a good idea.

Is there a certain design pattern or a better way to accomplish reading/updating screen data?

NOTE: Any code examples can be IronPython or C#. The conversion from C# to IronPython is pretty straight forward. Thanks!

+2  A: 

The BackgroundWorker is prefered when you have lot of work to do in the background.

Use a Timer to trigger a function that will do the necessary work in a second thread.

It won't block the UI. (don't forget to update the controls on the UI thread).

System.Threading.Thread newThread;
newThread = new System.Threading.Thread(anObject.AMethod);

http://msdn.microsoft.com/fr-fr/library/ms173178(VS.80).aspx

Pierre 303
Depends which Timer you use - winforms, threading and timers are the options.
Rob Fonseca-Ensor
+1  A: 

Another option rather than getting the Timer and the Background worker thread working would be to use the System.Threading.Timer, this will execute your method on a thread on a regular interval and once you have the data you can use Control.Invoke or Control.BeginInvoke to update the control in the UI thread.

Chris Taylor
+2  A: 

Personally, I'd have one thread that's responsible for reading values out of the device and storing the data in a data structure, and then a System.Windows.Forms.Timer (there's 3 Timers in .NET, this is the only one that ticks in the thread that's safe to update your controls) to read values out of that data structure and update the UI. You may need to synchronise that data structure, you may not.

That way the device can take as long as it likes to return data, or it can push as many millions of rows per second at you, and the UI thread will still poll at your predetermined tick rate (probably every 100 msec?). Since your timer ticks are just reading data out of memory, the UI won't block for IO.

Rob Fonseca-Ensor