I am having a problem with multi threading in C#. I use an event to update a label in a form from another thread, for which I need to use the Invoke() command of course. That part is also working fine. However, the user can close the form and here the program can crash if the event is sent at an unfortunate time.
So, I thought I would simply override the Dispose() method of the form, set a boolean to true within locked code, and also check that boolean and invoke the event in locked code.
However, every time I close the form the program freezes completely.
Here are the mentioned parts of the code:
private object dispose_lock = new object();
private bool _disposed = false;
private void update(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler handler = new EventHandler(update);
lock (dispose_lock)
{
if (_disposed) return;
Invoke(handler); // this is where it crashes without using the lock
}
return;
}
label.Text = "blah";
}
protected override void Dispose(bool disposing)
{
eventfullObject.OnUpdate -= update;
lock (dispose_lock) // this is where it seems to freeze
{
_disposed = true; // this is never called
}
base.Dispose(disposing);
}
I hope anyone here has any idea what is wrong with this code. Thank you in advance!