开发者

c# Invalid Operation Exception when closing my form

开发者 https://www.devze.com 2023-03-25 14:56 出处:网络
I have created a simple form that creates two classes A and B.Class A kicks off a Thread that fires and event every second.Class B subscribes to this event and updates a label.Code looks something lik

I have created a simple form that creates two classes A and B. Class A kicks off a Thread that fires and event every second. Class B subscribes to this event and updates a label. Code looks something like this:

class A...

public delegate void MyEventHandl开发者_如何学Goer(string text);
public event MyEventHandler MyEvent;
...
int i = 0;
if(MyEvent != null)
  MyEvent(i.ToString());
i++;

class B...

public delegate void MyEventHandler(string text);
void IncomingEvent(string text)
{
  if(InvokeRequired)
    Invoke(new MyEventHandler(IncomingEvent), text);
  else
    label.Text = text;
}

This code seems to work just as expected until i try to close the form. When closing my Invoke line throw an InvalidOperationException. I assume this is because my form is disposed of prior to my last event going off. I obviously can catch this exception and tuck it under the rug like it never happened but i'm curious on what the correct way in handling this is. Thanks in advance for the help.


If it is indeed disposed, try the IsDisposed property. (Form extends Control)

public delegate void MyEventHandler(string text);
void IncomingEvent(string text)
{
  if(IsDisposed)
    return;
  if(InvokeRequired)
    Invoke(new MyEventHandler(IncomingEvent), text);
  else
    label.Text = text;
}


Simply check if the form IsDisposed while you check InvokeRequired, and all should be well:

public delegate void MyEventHandler(string text);
void IncomingEvent(string text)
{
   if(!IsDisposed && InvokeRequired)
       Invoke(new MyEventHandler(IncomingEvent), text);
   else
       label.Text = text;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消