3

I have a client-server application, in which I use classic Sockets and threads for receiving/sending data and listening for clients.

The application works fine, but after some random time I get the ObjectDisposedException:

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'MainForm'.
   at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
   at System.Windows.Forms.Control.Invoke(Delegate method)

That code is called from client Socket thread and I use Invoke() method to run the code on UI thread.

I'm sure that I don't manually dispose the form nor using Close() (form is closed by user clicking Close button), so I don't know what could cause its disposing.

Edit: Exception isn't thrown during Form closing - it happens totally randomly.

mnn
  • 1,952
  • 4
  • 28
  • 51
  • Did you find a solution to this problem? I'm having a similar issue, although it is not with a form. Or do you even remember, as this was over a year ago. :) If not, no problem. – M3NTA7 Jul 28 '11 at 23:16
  • No, I don't remember what was the issue. However, I'm pretty sure, that the problem was within my code, that caused form to get disposed. So basically my solution wouldn't even be suitable for your problem. You should take another deep look into your code (with debugging, of course) and find the culprit. – mnn Aug 01 '11 at 11:48

2 Answers2

1

Have you tried overriding the Dispose method and putting a break point in there? The callstack would probably give you an indication of why/where it is being disposed.

James
  • 80,725
  • 18
  • 167
  • 237
0

I had a similar problem, I was just hiding a form and never closing it or disposing it.

The root cause of the form being disposed was due to a DialogResult of a Cancel button that actually was forcing the form Close and then the dispose was implicit.

To overcome this i just removed the DialogResult beaviour from the form.

Bruno
  • 56
  • 4
  • Even though I don't remember, what the cause was (so I can't really choose an answer, or write one myself), others might use it. So, thanks for the answer. – mnn Apr 08 '13 at 16:18