Given the C# code example:
using System;
using System.Threading;
using System.Windows.Forms;
public class MnFrm : Form
{
private void MnFrm_Load(Object sender, EventArgs e)
{
this.WorkCompleted += MnFrm_WorkCompleted;
}
private void btn_Click(Object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(AsyncMethod);
}
private void MnFrm_WorkCompleted(Object sender, Boolean e)
{
MessageBox.Show("Work completed");
}
private void AsyncMethod(Object state)
{
// Do stuff
Boolean result = true; // just as an example
WorkCompleted?.Invoke(this, result);
}
private event EventHandler<Boolean> WorkCompleted;
}
When the user clicks the button btn
the method AsyncMethod
is executed on another thread managed by the ThreadPool. After some time the work is done and the result is posted back via another event.
This event handler (WorkCompleted
) executes on the thread used to run AsyncMethod
because when the app is executed you get the 'Cross-Threading' exception.
So the question is how to run the event handler MnFrm_WorkCompleted
on the UI thread?