Answered by:
Trackbar vs NumericUpDown

Question
-
I currently use a NumericUpDown control on a Winform.
I was asked to change it to a Trackbar.
I have a background worker reading the value of the NumericUpDown control and it runs fine.
PlaybackIndex1 = NumericUpDown1.Value
When I replace the NUD with the Trackbar
PlaybackIndex1 = Trackbar1.Value,
I get the error message:
Cross-thread operation not valid: Control 'TrackBar1' accessed from a thread other than the thread it was created on.
Is there something different about the Trackbar?
Why am I not getting the same error message when using the NUD ?
.
Monday, May 20, 2019 7:27 PM
Answers
-
Hi
Here is one way to work with a BackGroundWorker to get a value from a main thread (UI) control.
In this example, I have a TrackBar1 control on the Form and to get the value inside the BackGroundWorker DoWork, I use
Invoke(Sub() TrackBarValue = TrackBar1.Value)
after which, the variable TrackBarValue holds the value.
*
I can't explain why MS have deemed it fitting for a NumericUpDown control on the main thread be readable within another thread with no Delegates or anything. I can confirm that that is the case though.
Regards Les, Livingston, Scotland
Monday, May 20, 2019 8:03 PM
All replies
-
Hi
Here is one way to work with a BackGroundWorker to get a value from a main thread (UI) control.
In this example, I have a TrackBar1 control on the Form and to get the value inside the BackGroundWorker DoWork, I use
Invoke(Sub() TrackBarValue = TrackBar1.Value)
after which, the variable TrackBarValue holds the value.
*
I can't explain why MS have deemed it fitting for a NumericUpDown control on the main thread be readable within another thread with no Delegates or anything. I can confirm that that is the case though.
Regards Les, Livingston, Scotland
Monday, May 20, 2019 8:03 PM -
Les,
Thanks!
I thought I was losing my mind, and I am glad you were able to firm that indeed NumericUpDown control is different.
Your solution works.
Is there a difference between
Invoke(Sub() TrackBarValue = TrackBar1.Value)
and
Invoke(Sub() TracBarValue = TrackBar1.Value
End Sub)
?
.
Monday, May 20, 2019 9:10 PM -
Hi
If the Sub() extends into more than a single line then youmwould need the End Sub - otherwise no difference.
Regards Les, Livingston, Scotland
Monday, May 20, 2019 9:27 PM -
Great.
I have been reading up on what you did with the Invoke.
It looks like what is contained in the Invoke is a lambda expression?
.
Also, the Invoke( ) that is inside the BackgroundWorker's DoWork,
can you explain is it the background worker that is doing the invoking?
I am usually seeing something like textbox1.invoke()
.
- Edited by ieee488 Tuesday, May 21, 2019 2:09 PM
Tuesday, May 21, 2019 1:26 PM