in Technology by
How do I update the GUI from another thread in C#?

1 Answer

0 votes
by

For .NET 2.0, here's a nice bit of code I wrote that does exactly what you want, and works for any property on a Control:

private delegate void SetControlPropertyThreadSafeDelegate(
    Control control, 
    string propertyName, 
    object propertyValue);

public static void SetControlPropertyThreadSafe(
    Control control, 
    string propertyName, 
    object propertyValue)
{
  if (control.InvokeRequired)
  {
    control.Invoke(new SetControlPropertyThreadSafeDelegate               
    (SetControlPropertyThreadSafe), 
    new object[] { control, propertyName, propertyValue });
  }
  else
  {
    control.GetType().InvokeMember(
        propertyName, 
        BindingFlags.SetProperty, 
        null, 
        control, 
        new object[] { propertyValue });
  }
}

Call it like this:

// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);

If you're using .NET 3.0 or above, you could rewrite the above method as an extension method of the Control class, which would then simplify the call to:

myLabel.SetPropertyThreadSafe("Text", status);

UPDATE 05/10/2010:

For .NET 3.0 you should use this code:

private delegate void SetPropertyThreadSafeDelegate<TResult>(
    Control @this, 
    Expression<Func<TResult>> property, 
    TResult value);

public static void SetPropertyThreadSafe<TResult>(
    this Control @this, 
    Expression<Func<TResult>> property, 
    TResult value)
{
  var propertyInfo = (property.Body as MemberExpression).Member 
      as PropertyInfo;

  if (propertyInfo == null ||
      [email protected]().IsSubclassOf(propertyInfo.ReflectedType) ||
      @this.GetType().GetProperty(
          propertyInfo.Name, 
          propertyInfo.PropertyType) == null)
  {
    throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
  }

  if (@this.InvokeRequired)
  {
      @this.Invoke(new SetPropertyThreadSafeDelegate<TResult> 
      (SetPropertyThreadSafe), 
      new object[] { @this, property, value });
  }
  else
  {
      @this.GetType().InvokeMember(
          propertyInfo.Name, 
          BindingFlags.SetProperty, 
          null, 
          @this, 
          new object[] { value });
  }
}

which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:

myLabel.SetPropertyThreadSafe(() => myLabel.Text, status); // status has to be a string or this will fail to compile

Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.

Unfortunately this doesn't stop anyone from doing stupid things such as passing in another Control's property and value, so the following will happily compile:

myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);

Hence I added the runtime checks to ensure that the passed-in property does actually belong to the Control that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.

Related questions

0 votes
    Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 19, 2022 in Education by JackTerrance
0 votes
    In SQL Server, it's possible to insert into a table using a SELECT statement: INSERT INTO Table (col1, col2, ... .id = other_table.id Select the correct answer from above options...
asked Jan 26, 2022 in Education by JackTerrance
0 votes
    Whenever we get a new release of code from our vendor, we need to perform basic tests to ensure ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 11, 2022 in Education by JackTerrance
0 votes
    Between Eclipse/SWT or Netbeans/Matisse, what does either Java GUI editor give you in terms of rapid ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 12, 2022 in Education by JackTerrance
0 votes
    I have a Composite Component that uses ajax to change multiple elements when an item is selected. I am ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 18, 2022 in Education by JackTerrance
0 votes
    In a multi user multi-threaded environment, thread safety is important as one may erroneously gain access to another ... (1)OS commands (2)Race conditions (3)Session Integrity...
asked May 17, 2021 in Technology by JackTerrance
0 votes
    Wordpress site. I want jquery or php, or any easy solution that will grab div from div id=content ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 17, 2022 in Education by JackTerrance
0 votes
    I have a dataframe with which if a cell has a value other than "." then I need python to return ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 3, 2022 in Education by JackTerrance
0 votes
    I want an efficient way to append one string to another in Python. var1 = "foo" var2 = "bar" var3 = var1 + ... built-in method to use? Select the correct answer from above options...
asked Feb 4, 2022 in Education by JackTerrance
0 votes
    what is the another name of weight update rule in adaline model based on its functionality? (a) LMS error learning ... (d) none of the mentioned Please answer the above question....
asked Sep 21, 2022 in Education by JackTerrance
0 votes
    If I have a table with results like this: 0001400OL 0578400OL 354085OL 48679OL and if I wanted to replace ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 26, 2022 in Education by JackTerrance
0 votes
    Designing a registration form, and I get this error when adding in MessageBoxButtons and MessageBoxIcon. The error ... for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 15, 2022 in Education by JackTerrance
0 votes
    Designing a registration form, and I get this error when adding in MessageBoxButtons and MessageBoxIcon. The error ... for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 6, 2022 in Education by JackTerrance
0 votes
    Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 11, 2022 in Education by JackTerrance
0 votes
    I am trying to use qt creator and python to generate flowcharts with values. I want to save the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 7, 2022 in Education by JackTerrance
...