We have a server application that communicates with clients via TCP sockets. After it runs for a few weeks it crashes with an NullReferenceException that can not be handled. I have been able to reproduce the exception with a very small console program, but it seems that there is unhandled exception in internal sockets threadpool. So I can not handle it with any try/catch blocks as it is not in my control.
Does anybody have any idea about this? Is it a framework bug or how can I catch the exception on the socket threadpool (so our application is not crashing) ? Here is the example code that is generating the exception, after a few iterations (3-10). It is important to know that the server is offline, so the socket is not being able to connect. It is used Visual studio 2010 and .Net framework 4.0.
internal class Program
{
private static string host;
private static Socket socket;
private static void Main(string[] args)
{
Trace.Listeners.Add(new ConsoleTraceListener());
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
host = "127.0.0.1";
//aslo the problem is happening whe the host is other network ip address
//host = "192.168.0.1";
//when in other thread doesn not crash application
//Task.Factory.StartNew(() => StartConnecting());
//also crashing the application
//Task.Factory.StartNew(() => StartConnecting(), TaskCreationOptions.LongRunning);
//when it is regular thread the exception occurs
///*
var thread = new Thread(new ThreadStart(StartConnecting));
thread.Start();
//*/
//when it is blocking exception also occurs
//StartConnecting();
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
private static void StartConnecting()
{
try
{
int count = 0;
while (true)
{
try
{
// if i must switch to Socket.Connect(...)?
Trace.WriteLine(string.Format("Connect Try {0} begin", ++count));
var ar = socket.BeginConnect(host, 6500, new AsyncCallback(ConnectCallback), socket);
Trace.WriteLine(string.Format("Connect Try {0} end", count));
}
catch (Exception err)
{
Trace.WriteLine(string.Format("[BeginConnect] error {0}", err.ToString()));
}
System.Threading.Thread.Sleep(1000);
//will see the exception more quick
}
}
catch (Exception e)
{
Trace.WriteLine(string.Format("[StartConnecting] error {0}", e.ToString()));
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string msg = e.ExceptionObject.ToString();
Trace.WriteLine(string.Format("[CurrentDomain_UnhandledException] isTerminating={0} error {1}", e.IsTerminating, msg));
Trace.WriteLine("Exiting process");
//the other processing threads continue working
//without problems untill there is thread.sleep
//Thread.Sleep(10000);
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Trace.WriteLine("[ConnectCallback] enter");
var socket = (Socket)ar.AsyncState;
socket.EndConnect(ar);
Trace.WriteLine("[ConnectCallback] exit");
}
catch (Exception e)
{
Trace.WriteLine(string.Format("[ConnectCallback] error {0}", e.ToString()));
}
}
}
After the application starts the inevitable crash will occur:
[CurrentDomain_UnhandledException] isTerminating=True error System.NullReferenceException: Object reference not set to an instance of an object.
at System.Net.Sockets.Socket.ConnectCallback()
at System.Net.Sockets.Socket.RegisteredWaitCallback(Object state, Boolean timedOut)
at System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object state, Boolean timedOut)