Search code examples
c#multithreadinginvokeimagelist

How do i call ImageList.Images.Clear() from another thread?


How do I call ImageList.Images.Clear() from another thread? I tried to do a function like

 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, System.Reflection.BindingFlags.SetProperty, null, control, new object[] { propertyValue });
        }
    }

but ImageList doesn't have an InvokeRequired or Invoke, plus I don't want to set a property, I just want to call

ImageList.Images.Clear()

Solution

  • You can use this:

    System.Threading.SynchronizationContext.Current.Post(o => ImageList.Images.Clear(), null);
    

    This will asynchronously invoke the delegate on the UI thread. If you need to immediately clear the list replace Post with Send. Of course you also need the reference to the ImageList you want to clear.