简体   繁体   中英

How to refresh my circular gauges while updating the needle value in threads (C# winforms)?

I use to make a project that reads some data from a serial port and displays these data on circular gauges. I made a thread for receiving data, a thread for sending data and a thread for each gauge to update the needle value.

I use 11 dotnet circular gauges and each gauge contain 2 scale with 2 pointers. In every thread of each gauge I made a loop that update the needle value slowly till it reaches the value I want without this loop the needle jumps suddenly to the value and I don't this to happen so +/- 0.003 on the current value of the pointer till it reaches the value.

My question is that when I run each gauge alone it works fine but when all gauges work at the same time the form freezes and then suddenly all pointers jump to the value how to handle this problem???? (I don't know why this happen it's supposed that each gauge works in a separate thread why the form freezes?)

I want to refresh the needles only not the whole gauge.

(each gauge represents a motor labeled from A to H) My code: http://ideone.com/GntXoE

Winforms does not support updating UI controls from a background thread. Whenever you want to update a UI control from a background thread, you need to pass a message from the background thread to the UI thread and perform the update of the control on the UI thread.

One way to do this is to use a System.Threading.SynchronizationContext . Capture the synchronization context into a variable while running on the main UI thread, then pass that context to each of your background threads. When a background thread needs to update a UI control, call context.Post and pass in a callback that will be executed on the UI thread.

Something like this:

context.Post(() => { control.Percent += 10; });

This will keep the UI work in the UI thread where the UI thread message loop will handle redrawing the form and controls as they change state. Using Post() instead of Send() will let your background thread get back to its task immediately without waiting for the UI work to complete. Send() will block the background thread until the UI work completes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM