I'm getting a Cross-thread operation not valid
error with a project I am working on.
Class MyObject
{
public delegate void MessageHandler(object sender, EventArgs e);
public event MessageHandler OnConnect;
public void Process()
{
await Connection();//Line highlighted when exception is raised.
}
private async Task Connection()
{
await 'blocking task here'
OnConnect(this, new EventArgs());
}
}
//Windows form
MyObject o = new MyObject();
o.OnConnect += o_OnConnect;
Thread connectionThread = new Thread(o.Process);
connectionThread.Start();
void o_OnConnect(object snder, EventArgs e)
{
listBox.items.add("Connection");
}
Is the basic overview. Note that the thread process here does other work than connecting, it's also handling some other business and needs to stay alive.
Everything goes ok, I initiate the connection on the background and I get the thread error when trying to add the listbox item.
Can anyone shed some light on this for me? The handler is on the form thread, where I can add/remove items from this box at will.
I've also changed the thread call line to
o.Process();
To remove the thread piece, but I get the exact same error.
I'm not sure if I'm missing something obvious or I'm way out in the weeds here. I really just want this thread to run some async code, and throw events back into where it was called from for processing.