0

I have a collection that raises an event every few seconds on a background thread. The event is then handled on the UI thread in a handler.

My handler checks if Control.InvokeRequired() then calls another method that does the actual update on the UI thread. All good.

The problem is in the 'if-invoke-is-required' statement.

The code works fine if I display the event data in the console, every few seconds it is updated as expected. If I try to invoke the UpdateUI method and pass the event data, it fires only once. What am I doing wrong here?

// delegate
public delegate void aDelegate(string a); 

// custom EventArgs
public class CollectionUpdateEventArgs: EventArgs
{
    public string Collection { get; set; }

    public CollectionUpdateEventArgs(string s)
    {
        Collection = s;
    }
}

// event handler (invoked every few seconds)
public void UpdateCollection(object sender, CollectionUpdateEventArgs a)
{
    aDelegate xyz;

    if (uiControl.InvokeRequired)
    {
        // this code works as expected, updates every few seconds
        // Console.WriteLine($"hello string {a.Collection}");
    
        // this code works once
        xyz = UpdateUI(a.Collection);
        uiControl.Invoke(xyz);
    }           
}

// update some UI component
protected aDelegate UpdateUI(string a)
{
    Console.WriteLine($"hello string {a}"); 
    return default;
}
ChrisB
  • 37
  • 3
  • 9
  • 2
    Please see duplicate for usable examples of how to update the UI from a worker thread. The code you have above completely misuses the concept of a delegate, returning a null reference from the `UpdateUI()` method, when you probably want a reference to a new delegate instance that uses that method as the target for invocation. IMHO, you should omit the `aDelegate` type altogether, as well as the check for `InvokeRequired`, and just _always_ use `Invoke()` like `uiControl.Invoke((MethodInvoker)(() => UpdateUI(a.Collection)));` – Peter Duniho Jul 30 '21 at 00:15
  • Thanks Peter, appreciate your feedback! – ChrisB Jul 30 '21 at 00:27

0 Answers0