473,738 Members | 7,110 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception when Form object is accessed after being disposed

Hi,

The problem is that the line -
this.Invoke(new MyDelegate(Func tion), args); // this = MainForm
is being called after the line -
terminatePopula te = true;

therefore I get an exception which states that MainForm has been
disposed when this.Invoke is called...

Is there a way to check if MainForm has been disposed. Perhaps theres
a better way of doing what am trying to achieve,

Thanks,

Aine

public class FormMain : Form
{
volatile bool terminatePopula te = false;

void FormMain_Load()
{

myThread = new System.Threadin g.Thread(MyThre ad());
myThread.Start( );
}

void MyThread()
{

while (!anotherObject .ContinueWaitin g)
{

if (!terminatePopu late)
this.Invoke(new MyDelegate(Func tion), args); // concerned
with control on Main Form
else
return;

Thread.Sleep(10 0); // Updates a control every 100 ms
}

if (!terminatePopu late)
this.Invoke(new MyOtherDelegate (Function), args);
}

private void OnClosing(objec t sender, EventArgs ev)
{
terminatePopula te = true;
}

}

Nov 13 '07 #1
5 5785
The problem here (aside from the synchronization issues that creep up in
setting terminatePopula te) is that in between the check on the value, the
form can be disposed of, which is causing your error.

Rather, what you should do is check the terminatePopula te value in the
delegate which gets called on the UI thread. This will cause you to not
access the form if the value is set.

Then, you can check the value in the loop on the thread in every
iteration to see if you should exit the thread.

You need to place a lock statement around access to the
terminatePopula te variable, as you need to synchrnoize access between the
threads.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<ai********@yah oo.comwrote in message
news:11******** **************@ v3g2000hsg.goog legroups.com...
Hi,

The problem is that the line -
this.Invoke(new MyDelegate(Func tion), args); // this = MainForm
is being called after the line -
terminatePopula te = true;

therefore I get an exception which states that MainForm has been
disposed when this.Invoke is called...

Is there a way to check if MainForm has been disposed. Perhaps theres
a better way of doing what am trying to achieve,

Thanks,

Aine

public class FormMain : Form
{
volatile bool terminatePopula te = false;

void FormMain_Load()
{

myThread = new System.Threadin g.Thread(MyThre ad());
myThread.Start( );
}

void MyThread()
{

while (!anotherObject .ContinueWaitin g)
{

if (!terminatePopu late)
this.Invoke(new MyDelegate(Func tion), args); // concerned
with control on Main Form
else
return;

Thread.Sleep(10 0); // Updates a control every 100 ms
}

if (!terminatePopu late)
this.Invoke(new MyOtherDelegate (Function), args);
}

private void OnClosing(objec t sender, EventArgs ev)
{
terminatePopula te = true;
}

}

Nov 13 '07 #2
I would have thought it would be better to terminate the Thread when
the form is disposed. There is a Disposing event for this I believe.
That way the thread can never be running after the form has been
disposed. It also holds better to the IDisposable interface where the
Dispose function is supposed to clean up all resources used by the
object.

I would also recommend that you look into using events to terminate
the thread correctly. You have no way at the moment of knowing when
the thread terminates and so can end up with a situation where the
object is completely destroyed and usless but the thread is still
running. You should at least have myThread.Join() in the closing
event.


Nov 13 '07 #3
<ai********@yah oo.comwrote in message
news:11******** **************@ v3g2000hsg.goog legroups.com...
Hi,

The problem is that the line -
this.Invoke(new MyDelegate(Func tion), args); // this = MainForm
is being called after the line -
terminatePopula te = true;

therefore I get an exception which states that MainForm has been
disposed when this.Invoke is called...

Is there a way to check if MainForm has been disposed. Perhaps theres
a better way of doing what am trying to achieve,

Thanks,

Aine

public class FormMain : Form
{
volatile bool terminatePopula te = false;

void FormMain_Load()
{

myThread = new System.Threadin g.Thread(MyThre ad());
myThread.Start( );
}

void MyThread()
{

while (!anotherObject .ContinueWaitin g)
{

if (!terminatePopu late)
this.Invoke(new MyDelegate(Func tion), args); // concerned
with control on Main Form
else
return;

Thread.Sleep(10 0); // Updates a control every 100 ms
}

if (!terminatePopu late)
this.Invoke(new MyOtherDelegate (Function), args);
}

private void OnClosing(objec t sender, EventArgs ev)
{
terminatePopula te = true;
}

}


Any reason why you are using Invoke instead of BeginInvoke?
Use BeginInvoke and set the flag in the FormClosing event handler.

Willy.
Nov 13 '07 #4
BeginInvoke will not change anything as it will just hide the
exception that still gets generated because the form has been
disposed.
Nov 14 '07 #5
"Olie" <ow****@gmail.c omwrote in message
news:11******** **************@ v2g2000hsf.goog legroups.com...
BeginInvoke will not change anything as it will just hide the
exception that still gets generated because the form has been
disposed.


Invoke has Synchronous call semantics, that is it waits until the delegated
callback returns, the caller is *assumed* to handle the return value and the
exception thrown by the callback .
BeginInvoke has "fire and forget" semantics, that means that the caller does
not care about whatever the delegate returns. In the OP's scenario, all he
needs is an event that indicates that he can stop updating the UI.
If he would like to get the result of the delegate (which can only be an
exception here), he would have wrapped the UI call in a try\catch block
anyway.
There is no easy way to prevent this race. There is no way to control the
sequence of the messages as stored in the Windows Message Queue. WM_CLOSE
message (queued by SendMessage) are always handled before Posted message (as
used by Invoke/BeginIvoke), that means that the already queued
"ThreadCall Back Messages" will be postponed till after the WM_CLOSE has been
processed and as such after the Control has been disposed. Whenever the
Windows loop picks up the previously queued "ThreadCallBack " message and
starts executing the callback it will get a "ObjectDisposed Exception"
thrown on him, all you can do here is catch the exception in the delegated
function.

Willy.

Nov 14 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3358
by: Eric Cadwell | last post by:
We're running Load Runner to test a large 1.0 based WinForms application. I'm getting the following exception when opening and closing a form 400 - 450 times. The form contains several controls and custom UserControls. All the code is native C#. I'm not making an explicit call to ToBitmap or DrawIcon in my code. Can anyone help? Exception Caught in Main(): at System.Drawing.Graphics.GetHdc()
1
536
by: Rafael | last post by:
Hi, I hope I can find some help for this problem IDE: Visual Studio.NET 2003 Developer Editio Language: C# Problem: "An unhandled exception of type 'System.NullReferenceException' occurred in system.windows.forms.dll. Additional information: Object reference not set to an instance of an object. Visual Studio's IDE is not allowing me to develop projects in C#... I've trying to create a simple Windows Forms project using Visual Studio.NET...
7
22744
by: Ryan Park | last post by:
Hi, //SITUATION I got a panel control that hold a certain position on a form. Every controls or UIs are on this panel. At certain situation, I called dispose() method of this panel control and change it with other panel which contains other business logic and UI controls.
5
6112
by: mthgk | last post by:
I have a C# MDI app. The child forms do alot of work, so this work is perfomed on a different thread created using ThreadPool.QueueUserWorkItem(). Because the status of the work is important to the user, I post the results in a richTextBox on the child form. I have created an event to do this since it is best to update the controls using the thread that they were created with (or so I've read). Anyway, the first time the user selects a...
1
1714
by: bw | last post by:
I have a basic custom collection that throws a new exception if the item(key) is not found in the collection. This is used as part of a calling function. It all works correctly, the problem (discovered using a memory profiler) is that the base exception being thrown in the collection is not being disposed of. I understand about the GC etc etc. It appears that something is hanging on to a reference to System.Exception and a...
8
1766
by: bole2cant | last post by:
When I add a Button to my NotifyIcon program I get the following: An unhandled exception of type 'System.NullReferenceException' occurred in unknown module. Additional information: Object reference not set to an instance of an object. I suspect this is a common novice error but I haven't any idea what I need to do to get this to work. "Help" seems to be geared toward people who have been coding for a couple of years!
7
5229
by: Boni | last post by:
Dear all, if I do myform.close() is it disposed or not? is it correct do following? myForm.close() Info=SomeControlOntheForm.text This seems to work. But am not sure that it is waterproof. Thanks, Boni
5
7928
by: pcnerd | last post by:
I'm trying to create a program that plots randomly colored pixels on a bitmap & then displays the bitmap. When I run the program, I see the pixels being plotted down the left side of the form. When it gets to the bottom, the "Argument out of range exception" occurs. So, obviously the program starts. The Help tells me that the argument isn't within the range of values, but it doesn't explain how to fix the problem. So the Help doesn't help!...
6
2432
by: ahmad.humyn | last post by:
I want to call a hidden form. My code goes something like in which the main calls form1. form1 has a button which creates & calls form2 and hides itself. Now I have a button in form2 which if pressed should dispose form2 and then unhide and focus form1. -------------------------------------------------- static void Main() { ..... Application.Run(new Form1());
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.