C# – How to reduce interface lag in C#

cnettimeruser interface

I have a problem with interface lag in C#.

Since I'm still learning please be patient whilst I explain.

I have narrowed the problem to my timer object.

Basically my program queries a device through TCP/IP socket and outputs it to a textbox on screen.

Now I am polling the device for data every second which requires some logic to be buried within timer object and the following is what happens between ticks:

  1. Increment a value.
  2. Construct the 2 strings that represents the command to be sent to
    the box (encapsulated in a function
  3. Encode the command
  4. Send command
  5. Clear the byte array
  6. Receive reply.

Could this be too much processing being done in the event handler? Every time I try to move the window during the polling session i.e. when the timer is running I get a very bad input lag.

Best Answer

The timer you are using is executing on the windows message thread. Therefore, while the polling is running the windows message queue is blocked. This isn't a problem with doing too much processing, most of the time the thread will be waiting for the TCP/IP response.

To fix this, you just have to do the do the work on a background thread and then update the UI on the UI thread.

There are a heap of different timers in the .NET framework that work in different ways, the one you are using works processed the timer event on the same thread, others work on background threads. Check this article out about the different timers.

You could also just use your current timer to invoke a BackgroundWorker component to do the work on the background thread. The main benefit of this is the the BackgroundWorker will do the work on a background thread, but will raise the work complete event on the UI thread so that it is simple to update the UI without having to worry about which thread you are on.