Handling device communication and GUI updates seperately in C#

I'm developing an application that scans images from connected scanners on well defined time intervals, say every 5 minutes, for a specified amount of time. While my app is running I have a label (timerlabel) counting down the total time of the project left, and this is handled by a DispatcherTimer which updates the label every second.

The scanners are handled by another DispatcherTimer which every five minutes will call a function Scan() for each scanner. When this function is called the scanning starts, but the GUI stops updating, and the timerlabel freezes for the duration of the scan. When it starts again it just keeps counting down, not having registered the time that elapsed when the scanning was in progress.

How can I make the timerlabel keep running while the scanning is in progress?


Try spawning a background thread. Instead of havinhg your DispatchTimer call Scan() directly, have it call BeginInvoke() on a delegate or lambda that calls Scan(). Now, Scan() will run in a different thread, leaving the UI thread free to respond to graphics messages.

If Scan() will update UI controls, such as images or textbox text, you will need to have any such logic encapsulated in a delegate that you pass to your window's Invoke() method. This will prevent "cross-threading", which is dangerous when dealing with the UI and causes exceptions to be thrown by the runtime.

Although not being sure to get the full story I would try to start your Scan() method by a BackgroundWorker, which has support for progress metering via delegates baked in, created when the corresponding DispatchTimer() has fired.

Need Your Help

How to get Main Window in UserControl

c# .net wpf

I have got some generic User Control under the Canvas of the WPF window.

How to encrypt/decrypt files with PBE AES using BouncyCastle Lightweight API?

java encryption cryptography aes bouncycastle

I'm trying to encrypt/decrypt files with PBE using AES. I'm using Bouncy Casle library(lightweight API), because I need to ignoring restrictions on key length. I found function and changed some cod...