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