C# SetPropertyThreadSafe vs Invoke thread-safe calls

830 views Asked by At

Which of these two methods are better to update the UI from another thread? (for me they work both, but which is safer?) I would prefer the SetPropertyThreadSafe method as it needs less code.

1.

label1.SetPropertyThreadSafe(() => this.label1.Text, "New Value");

2.

if (label1.InvokeRequired)
{
   label1.Invoke(new MethodInvoker(delegate {
   label1.Text="New Value"; }));
}            
2

There are 2 answers

0
Scott Chamberlain On BEST ANSWER

SetPropertyThreadSafe is not a method built in to .NET, if you are using this implmentation

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);
    }
}

Then the two examples you posted are doing the exact same thing so there is no difference.

3
Ian Ringrose On

If you head

1.

label1.SetPropertyThreadSafe(() => this.label1.Text, "New Value");
label2.SetPropertyThreadSafe(() => this.label1.Text, "New Value2");

and 2.

if (label1.InvokeRequired)
{
   label1.Invoke(new MethodInvoker(delegate 
   {
   label1.Text="New Value"; 
   label2.Text="New Value2"; 
   }));
}    

Then (2) is clearly better as it has a much lower overhead. But in your case there is nothing to choose between them.

If you know you are on another thread, there is no need for the "if InvokeRequired".