7

I am working with Windows Forms, and many times have bumped into (as I understood it) the necessity to write wrapping functions around properties of the UI components, so that they (the properties) could be set from another thread by invoking their wrappers.

However, one thing doesn't give me rest. Are not the setters of properties actually functions themselves? If they are, could a Delegate be formed around them without resorting to writing wrappers, and then said delegate be invoked from another thread?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Srv19
  • 3,458
  • 6
  • 44
  • 75

2 Answers2

6

Yes, this is possible. Use the PropertyInfo.GetSetMethod function to retrieve the set accessor for the property, and then create a delegate to invoke it.

Or even simpler yet, you could use the PropertyInfo.SetValue function to set the value directly.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
3

I can't find the real solution for this question but I figured it out. I sometimes need it myself but Google fails me.

Example:

public string Blah
{
    get
    {
        if (InvokeRequired)
            return (string) Invoke(new Func<string>(() => Blah));
        else
            return Text;
    }
    set
    {
        if (InvokeRequired)
            Invoke(new Action(() => { Blah = value; }));
        else
            Text = value;
    }
}
Bitterblue
  • 13,162
  • 17
  • 86
  • 124
  • 3
    This is not what I asked for. I want to (1) take an existing property, (2) *extract* the getter and/or the setter as independent delegates. No amount of cleverness *inside* of the property is going to help me achieve do that. The real job has to be done *outside* of the property. – isekaijin Oct 13 '14 at 16:22
  • Well, there is always the old-fashioned way of defining getter and setter, and then (if you want syntactic sugar) invoke them in property definition. Beggars can't be choosers, i guess – Srv19 Oct 13 '14 at 19:55
  • That won' help my original problem in any way, though. – Srv19 Oct 13 '14 at 19:56
  • 2
    @Srv19 Well, it was what _I_ was looking for. And it's **pretty much** what the title and at least the first paragraph of this questions ask for. You can overwrite existing properties with the new keyword or do this from the outside `if (form1.InvokeRequired)` I'm happy when people suggest more than one way to solve things and even other people are looking for ways to solve problems not always your or my way. – Bitterblue Oct 14 '14 at 07:09
  • @Bitterblue Maybe it doesn't answer the original question, but helped me to solve my problem. Thank you. – woelfchen42 Mar 27 '23 at 09:18