Winforms - what is the easiest way to update a property in streaming mode

I have the following code that I used to set properties in streaming safe mode (adapted from this other SO question , but I cannot adapt it to get the property.

This is my set property in safe thread 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); } } 

Called as follows:

 this.lblNameField.SetPropertyThreadSafe(p => p.Text = "Name:"); 

This is my attempt to get the property in thread safe 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); } } 

This does not work. I would hope to call it by doing the following:

 string name = this.lblNameField.GetPropertyThreadSafe(p => p.Text); 
+4
source share
1 answer

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 like this:

 bool visible = this.lblNameField.GetPropertyThreadSafe(p => p.Visible) 
+3
source

Source: https://habr.com/ru/post/1396684/


All Articles