Reputation: 2953
I have the following code that I have been using to Set properties in a thread safe manner (adapted from this other SO question, but I cannot adapt it to get the property.
This is my set property in thread safe way code.
public static void SetPropertyThreadSafe(this TControl self, Action setter)
where TControl : Control
{
if (self.InvokeRequired)
{
var invoker = (Action)(() => setter(self));
self.Invoke(invoker);
}
else
{
setter(self);
}
}
Which is called by doing the following:
this.lblNameField.SetPropertyThreadSafe(p => p.Text = "Name:");
This is my attempt at a get property in thread safe way code.
public static TResult GetPropertyThreadSafe(this TControl self, Func getter)
where TControl : Control
{
if (self.InvokeRequired)
{
var invoker = (Func)((TControl control) => getter(self));
return (TResult)self.Invoke(invoker);
}
else
{
return getter(self);
}
}
It doesn't work. I'd hopefully like to call it by doing the following:
string name = this.lblNameField.GetPropertyThreadSafe(p => p.Text);
Upvotes: 4
Views: 1311
Reputation: 564441
You should be able to use:
public static TResult GetPropertyThreadSafe<TControl, TResult>(this TControl self, Func<TControl, TResult> getter)
where TControl: Control
{
if (self.InvokeRequired)
{
return (TResult)self.Invoke(getter, self);
}
else
{
return getter(self);
}
}
You call it by the following:
bool visible = this.lblNameField.GetPropertyThreadSafe(p => p.Visible)
Upvotes: 3