views:

413

answers:

1

I have a PropertyGrid that is setting control's properties of a control on another form. However for things such as "Location" and "Text", I get a cross threading issues.

Is there an easy way to safely (not using AllowIlligalCrossThread=true) let the setting of these properties occur with the property grid?

Thanks.

A: 

You could create a derived subclass which overrides the properties and uses Invoke to set the properties in a "thread-safe" manner.

class DerivedLabel : Label
{

    public override string Text
    {
        get
        {
            return Invoke(new Func<string>(GetText)) as string;
        }
        set
        {
            Invoke(new Action<string>(SetText), value);
        }
    }

    private void SetText(string text)
    {
        base.Text = text;
    }

    private string GetText()
    {
        return base.Text;
    }

}

Invoke() runs the delegate that you pass on the same thread that created the control, so it's implicitly thread-safe. However, this could be a lot of work if you have a lot of controls you need to subclass.

It would probably be better worth your time to figure out why you are getting threading issues - if both controls are created on the same thread (as is normal for a Windows app) you shouldn't be getting these exceptions. Are you creating the PropertyGrid form on a different thread for some reason?

Chris Vig