threading and UI calls

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
 
B

Brian Gideon

Jim,

You are right. The first example is wrong, but the second is correct.

Brian
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top