
Originally Posted by
CVMichael
I can't figure out how to send events from a worker thread to the UI thread.
That's because there is no such thing. Events are defined like so:
csharp Code:
public event EventHandler SomethingHappended;
protected void OnSomethingHappened(EventArgs e)
{
SomethingHappened?.Invoke(this, e);
}
The OnX method is where the X event is actually raised. When you want to raise that event, you call that method:
csharp Code:
// Do something here.
// Raise the event.
OnSomethingHappened(EventArgs.Empty);
In code that can or will execute on a secondary thread, you can marshal a method call to the UI thread to execute code on the UI thread. That method can do whatever you want. It's just a method. If you want to raise your event in that method, do so, just as I showed above:
csharp Code:
private void RaiseSomethingHappened()
{
OnSomethingHappened(EventArgs.Empty);
}
and:
csharp Code:
Invoke(RaiseSomethingHappened);
Alternatively, you could use a lambda to call the method that raises the event directly:
csharp Code:
Invoke(() => OnSomethingHappened(EventArgs.Empty));
In summary, you "send" a method call to the UI thread, just as you always do, then raise the event in that method, just as you always do.