Saturday, July 21, 2007

Windows Forms: "Cannot access a disposed object"

Well, good question what to do ... within forms i'm using normally a regular singleton factory after I received the following exception: "Cannot access a disposed object" I extended my code to the following:


#region Property: NetworkOverview
private NetworkOverview networkOverview ;
///


/// Gets/sets the NetworkOverview
///

public NetworkOverview NetworkOverview
{
[System.Diagnostics.DebuggerStepThrough]
get {
if (this.networkOverview == null)
this.networkOverview = new NetworkOverview();
if (this.networkOverview != null && this.networkOverview.IsDisposed)
{
this.networkOverview = null;
this.networkOverview = new NetworkOverview();
}

return this.networkOverview ;
}
}
#endregion

2 comments:

bart said...

Hi, thanks for sharing.

You can make it even shorter.

Just use one if statement like this.

if (this.networkOverview == null || this.networkOverview.IsDisposed)
{
this.networkOverview = new NetworkOverview();
}

further, you can also avoid the disposing in the onclosing event

in the event use e.Cancel = true;

Cheers, Bart

spin doc said...

thx much for the insight, using the FormClosing action works very well

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge