Reputation: 83
I'm having a "invoke" issue that I can't resolve. I'll try to be as thorough in my description as possible, but I'm new to this so bear with me and let me know if you need more information.
I've got a background thread running that when prompted will disable a bunch of check boxes on a form created on the main thread. In order to do this I need to safely cross-thread using an invoke
and a delegate but I must be doing it incorrectly. Bottom line, when I check this in the debugger i see that it runs through the ACTION portion of the code twice if InvokeRequired
. I can get around this by bracketing ACTION with an else
, and although it won't run through the else
twice it does still try to go through the method again.
delegate void ManualCurtainShuttoffHandler();
public void ManualCurtainShutoff()
{
if (InvokeRequired)
{
Invoke(new ManualCurtainShuttoffHandler(ManualCurtainShutoff));
}
// ACTION: Disable check boxes
}
I'd just like to know why it runs through the method two times. Let me know if you need any more information and I'd be happy to share it with you.
Upvotes: 4
Views: 5074
Reputation: 4600
Invoke will cause your function to be called again in a different thread (that's its purpose). You should add a return after the call to Invoke. The idea is that then your function will be called again (that's what you want), and that time InvokeRequired will be false, so your action will take place.
edit: dang, by the time I finish writing I've been beaten to the punch. Oh well!
Upvotes: 6
Reputation: 23198
Just because you call Invoke
, it doesn't stop execution of the current method. A quick and simple solution is to simply return
after calling Invoke
:
delegate void ManualCurtainShuttoffHandler();
public void ManualCurtainShutoff()
{
if (InvokeRequired)
{
Invoke(new ManualCurtainShuttoffHandler(ManualCurtainShutoff));
return;
}
// ACTION: Disable check boxes
}
This will skip the rest of the execution of ManualCurtainShutoff
that's running on the background thread while still promoting a new execution of the method on the main thread.
Upvotes: 11