0

I have big trouble with my class library which is using to getting and sending text messenges through sockets. Here is my simple code :

private void AcceptNewSocket()
{
    Socket socket = list.AcceptSocket();
    socket.ReceiveBufferSize = 1001;
    Thread socketTh = new Thread(new ThreadStart(AcceptNewSocket));
    socketTh.Start();
    WaitForMessenge(socket);
}

private void WaitForMessenge(Socket socket)
{
    byte[] buff = new byte[1001];
    int bufcount = socket.Receive(buff);
    /////////some operations on byte array
    while(bufcount > 0)
    {
      buffcount = socket.Receive(buff); //HERE it throws ObjectDisposedException and source is socket
      /////some operations on byte array
    }
 }

There isn't any exception when i use my library in console application. It occurs when i use it in Windows Forms application. Can you help me ?

MethodMan
  • 18,625
  • 6
  • 34
  • 52
mp__mp
  • 1
  • 1
  • Just give up and use something like Lindgren for your networking. Working with raw sockets is anything but easy. – Luaan Jan 30 '15 at 16:41
  • 1
    If the socket is closed anywhere else, calling Receive method will give you that exception. Make sure you check if the object has been disposed before using it. – Lex Li Jan 30 '15 at 16:47
  • I'm don't closing it. It runs pretty good in comunication between console applications. – mp__mp Jan 30 '15 at 17:30
  • @LexLi - Sadly, there is no `socket.IsDisposed` property to check, because the `IDisposable` interface does not declare it. I always add `public bool IsDisposed { get; private set; }` to my disposable classes, and start the `protected virtual void Dispose(bool) { if (IsDisposed) return; IsDisposed = true; ... }` – Jesse Chisholm Mar 25 '15 at 17:14

1 Answers1

0

AcceptNewSocket() looks really suspicious to me. I strongly recommend to review it.

What does list.AcceptSocket() do? This could be a possible location for disposing your socket.

Why do you create Threads recursively? This could make dozens of threads so they will throw exception when socket is disposed.

And well... Apart from this I would use ThreadPool class instead of Threads for better preformance.

Alex K.
  • 784
  • 5
  • 12
  • sorry. "list" is my tcplistener object. When i don't create new threads this exception occurs too. – mp__mp Jan 30 '15 at 16:53
  • @Wynglarz - Alex's point about **Why do you create Threads recursively?** is not that you shouldn't create a thread, but that you shouldn't create a thread **inside** `AcceptNewSocket()` whose work method is the very same `AcceptNewSocket()`. That causes infinte recursion, and the first call to `AcceptNewSocket()` will chew up resources until your application dies. – Jesse Chisholm Mar 25 '15 at 17:18