Reputation: 23
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
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
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
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