Make MenuStrip Thread-Safe

  • Thread starter Thread starter Ahmad Jalil Qarshi
  • Start date Start date
A

Ahmad Jalil Qarshi

Hi,

I have a Windows Form based C# application which has a MenuStrip component.
I have a child thread running in the application.

Now I have to Enable/Disable the ToolStripMenuItem from within the Child
Thread. The problem is that since it doesn't have an InvokeRequired property
like other Form Controls, hence I can't use that to make it threadsafe.

So isn't it possible to make it threadsafe? If so then what's the best
possible way?

Thanks in anticipation.

Regards,

Ahmad Jalil Qarshi
 
Ahmad,

A good way to do this is to store the value of the static Current method
on the SynchronizationContext class in a field that is accessible by the
method you want to call on the other thread. You need to make sure to make
the call to Current on the UI thread.

Then, in the worker thread, look at the SynchronizationContext you
stored. If you want to do a check to see if invoking is required, then you
can get the SynchronizationContext for the current thread, compare it with
the stored value. They will be different if they are for different threads
(they ^should^ be the same if they are not for different threads, but you
have to check this).

Or, you could just have a control reference you know the menu is on in
the worker thread, and call InvokeRequired on that.
 
I have a Windows Form based C# application which has a MenuStrip
component.
I have a child thread running in the application.

Now I have to Enable/Disable the ToolStripMenuItem from within the Child
Thread. The problem is that since it doesn't have an InvokeRequired
property
like other Form Controls, hence I can't use that to make it threadsafe.

MenuStrip has both InvokeRequired and Invoke, being a class that inherits
the Control class. So I'm a little confused by your statement that it
doesn't. Or if you're talking about the ToolStripMenuItem, you just need
to get the Owner of that instance, and that Owner (being a ToolStrip
instance and thus derived from Control) will have InvokeRequired and
Invoke().

Nicholas's suggestion about SynchronizationContext is a good thing to know
if you need to do this sort of thing where there's no GUI involved. But
I've yet to run across a situation when using classes in the Forms
namespace where those classes don't somehow provide a reasonably
convenient way to get a Control instance that can be used to Invoke()
cross-thread methods. I think this is not one of those situations
either. :)

Pete
 
Back
Top