Trying to get started with threads but UI thread giving cross thread exceptions?
I have a thread that runs infinitely and what i believe is happening is that the new thread means events run on it leading to cross threading exceptions but i dont understand why that thread cant run in the background and events stay running on the main ui thread?
This is the test i am using for my new thread
and my throttle event handler is giving me threading exceptions but its on the main ui thread right?
20 Replies
What is the exception saying?
{Value = {"Cross-thread operation not valid: Control 'TRACKBAR_Throttle' accessed from a thread other than the thread it was created on."} Min = 0 Max = 100}
@Nasdack
TRACKBAR_Throttle
is a UI control that is created from within the main thread
What UI framework are you using?winforms
Controls in WinForms provide an Invoke method so you that there you can execute actions on the thread from which they were created
okay so would i have to modify every single one of my methods
and invoke them?
No
I'm on my phone
What you can do
Is wrap the whole event handler method
With
TRACKBAR_Throttle.Invoke(() => { // existing method code});
would i do this for all events?
Any event that creates its own thread, yes
sorry just to make sure so i have this calculation thread and everything else on the ui thread, and so all events that need to be on ui thread need to be invoked because they canbe called whilst the calculation thread is running
If your calculation is running in its own thread, and it tries to invoke an event, that event will run on the thread that of the calculation logic, not that of the UI.
ah okay so i must invoke all my ui events becuase the calculation thread is always running
is there a cleaner way to do this or is that it
Not all of them, just the ones that are invoked by the calculation thread.
What's unclean about it?
the calculation thread doesnt invoke any though so im confused
they can be invoked whilst the calculation thread is running but not by it
That is weird
Not sure why
But that fixes your problem anyway
okay thank you very much
ill try that now
Np
@Nasdack
there's a multitude of overloads your syntax is most likely incorrect
Send the rest of the code