Reputation: 1985
So I have a socket server running, inside an asp.net ( C# ) application (very bad approach) that notifies any device connected, It was like that when I started working at this company and changing it is not on a priority to my supervisors even though it will be better.
So what happens is when we do an update to the Website the Socket connection stays open (in another thread), then we have to restart the Server, but what I want to do is somehow get the Thread ID on startup of the Socket, then store it, if the update is done it should reattach to that thread and end the Socket somehow or reset it.
Is this possible?
this is sample code
private void Start()
{
_socketServer = new TcpListener(IPAddress.Any, Convert.ToInt32(ConfigurationManager.AppSettings["NotificationSocketPort"]));
_socketServer.Start();
_acceptingThread = new Thread(() =>
{
while (true)
{
try
{
var client = _socketServer.AcceptTcpClient();
StartClient(client);
}
catch (ObjectDisposedException ex)
{
_acceptingThread = null;
_socketServer = null;
Start();
break;
}
}
});
_acceptingThread.Start();
}
public void Close()
{
if (_acceptingThread != null)
{
_acceptingThread.Abort(0x0);
_socketServer.Stop();
_acceptingThread = null;
_socketServer = null;
}
}
In global.asax
protected void Application_End(object sender, EventArgs e)
{
SocketNotifier.GetNotifierInstance().Close();
}
The SocketNotifier is using the Singleton Design Pattern
Upvotes: 2
Views: 96
Reputation: 171178
They [the sockets] stay open that is the problem after IIS worker process terminates and a new one is started
Probably, IIS has trouble shutting down the old process. That keeps the socket open. Your socket thread is a foreground thread. It does not prevent process termination. Also, aborting a thread does not affect IO. And your socket listening method automatically restarts itself when the socket is closed.
Remove these problems. Make the thread a background thread. Don't abort it. Don't restart it in case of an ObjectDisposedException
.
Upvotes: 1
Reputation: 1062550
Frankly, this is just the wrong approach. Web apps restart, and should be expected to restart. Sockets don't like that, and should not be expected to like that. Your best bet here would be to re-write the socket code as a windows service - that way it can keep running independently of the web-app.
Upvotes: 2