threading and UI calls

  • Thread starter Thread starter Jim H
  • Start date Start date
J

Jim H

About a year back I posted a question and eventually implemented the
following code in an event handler as a result:

object[] some_args = new object[1];
some_args[0] = my_event_args.results;
ISynchronizeInvoke lSync = this as ISynchronizeInvoke;
if(lSync == null)
{// UI Thread
UIDelegate.DynamicInvoke(some_args);
}
else
{// Worker thread
this.Invoke(UIDelegate, some_args);
}

Reading the code now I'm questioning it. Can lSync ever be null if the code
is in a WinForm derived class. Other examples I am seeing all do a check of
InvokeRequired before calling Invoke. Since I am in the form code lSync can
never be null, correct? Therefore, in my current code, I am always calling
this.Invoke. I have changed the code to check InvokeRequiredbefore calling
Invoke. If InvokeRequired is false I just make the call directly.

My new code:
object[] some_args = new object[1];
some_args[0] = my_event_args.results;
ISynchronizeInvoke lSync = this as ISynchronizeInvoke;

if(lSync.InvokeRequired)
{// Worker thread
lSync.Invoke(UIDelegate, some_args);
}
else
{//gui thread
MyHandler(my_args.results);
}

Is this correct? This just seems to have less overhead than always calling
invoke.

Thanks,
jim
 
Jim,

Form derives ultimately from Control, which implements
ISynchronizeInvoke. You don't have to check to see if it implements it.

As for your code, you don't have to cast to ISynchronizeInvoke, as
Control/Form implements the interface implicitly (so you can call it right
off the "this" reference).

Hope this helps.
 
Back
Top