Question about Control.IsDisposed

S

Sam Sungshik Kong

Hello, folks!

I am trying to understand how IsDisposed property of Control class works.
I need to use the following code in my application.

if frm == null or frm.IsDisposed
...

MS explains about IsDisposed like the following.

<snip>
When this property returns true, the control is disposed of and can no
longer be referenced as a valid Windows control. Even though the instance of
a control is disposed of, it is still maintained in memory until it is
removed from memory through garbage collection.
</snip>

I don't understand several things regarding above explanation and
IsDisposed.

1. Is a control maintained in memory even after it's disposed?
2. If a control is garbage collected, how can I access the IsDisposed
property (property is part of control)?
3. Can I rely on the code (if frm == null or frm.IsDisposed) when I want to
check if the frm is created and accessible?

Thanks.

Sam
 
M

Morten Wennevik

Hi Sam,
1. Is a control maintained in memory even after it's disposed?

1. Yes, you can call Dispose() on a control and still have a reference to it. The Dispose method
"Disposes of the resources (other than memory)". It is used to speed up garbage collection and to free file handles and resources not cleaned up by the garbage collector.
2. If a control is garbage collected, how can I access the IsDisposed
property (property is part of control)?

In theory, you can't, since if you had a reference to the object you want to check IsDisposed of, then the garbage collector wouldn't have released it.
3. Can I rely on the code (if frm == null or frm.IsDisposed) when I want to
check if the frm is created and accessible?

Someone else would know more than me on this, but I would imagine

if(frm != null)
{
if(!frm.IsDisposed)
{
// form is still working
}
}

There might be more to it though, especially in multithreading.
 
J

Jon Skeet [C# MVP]

Morten Wennevik said:
Someone else would know more than me on this, but I would imagine

if(frm != null)
{
if(!frm.IsDisposed)
{
// form is still working
}
}

I don't think there's any benefit in breaking it up into two stages
here. Just use

if (frm!=null && !frm.IsDisposed)
{
....
}
There might be more to it though, especially in multi-threading.

If you need to know about it from a non-UI thread, you'd need to use
Control.Invoke - but by the time the delegate returned, the result
might be wrong!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top