Bill Adonopoulos
Bill Adonopoulos

Reputation: 23

StackOverflowException in System.dll

So here i have a problem with my C# code.. It's repeating a thread for accepting new connections But it gets StackOverflowException in System.dll after some minutes

Here is my code

void DoReceive(SocketAsyncEventArgs args)
{
    var client = (TCPClient)args.UserToken;
    System.Threading.Thread.Sleep(10);
    if (!client.socket.ReceiveAsync(args))
    {
        //System.Threading.Thread.Sleep(10);
        DoReceive(args);
    }
}

Upvotes: 1

Views: 480

Answers (3)

Akrem
Akrem

Reputation: 4652

DoReceive called repeatedly if !client.socket.ReceiveAsync(args) then if this result not changed will raise StackOverflowException

the same Idea that Olexander give

void DoReceive(SocketAsyncEventArgs args)
 {   
    var client = (TCPClient)args.UserToken;        
    while (!client.socket.ReceiveAsync(args))
     {
       System.Threading.Thread.Sleep(100);
     }
}

Upvotes: 1

Olexander Ivanitskyi
Olexander Ivanitskyi

Reputation: 2240

Endless recursion leads to StackOverflowException. Consider changing you code:

void DoReceive(SocketAsyncEventArgs args)
{
    var client = (TCPClient)args.UserToken;        
    while (!client.socket.ReceiveAsync(args))
    {
        System.Threading.Thread.Sleep(10);
    }
}

Upvotes: 2

Vimal Stan
Vimal Stan

Reputation: 2005

DoReceive is being called recursively every time ReceiveAsync returns false. It looks like ReceiveAsync is returning false more often than not, causing your program to run out of memory.

From MSDN

[StackOverflowException] "is thrown when the execution stack overflows because it contains too many nested method calls"


You could set a static variable to keep a count of retries and quit after you reach a limit.

Upvotes: 0

Related Questions