asp.net-mvcmultithreadingsocketsiislong-running-processes

Long running background thread terminated in ASP.NET


I've built an ASP.NET MVC web server that connects to a hardware device via a socket. The idea is to spawn a thread that opens a socket and listens for TCP packages from the hardware. Since the hardware performs a long-running task that takes a significant amount of time to complete (years), I want to keep the thread alive as long as possible to monitor the process using SignalR and save some data to the database.

To achieve this, I've created a thread as follows:

rs = new TcpListener(IPAddress.Any, PORT_DATA_NUMBER());
rs.Start();  
Thread thread = new Thread(() => ListenerHandleConnections(rs));  
thread.IsBackground = true;  
thread.Start();

The thread workflow is as follows:

public static void ListenerHandleConnections(TcpListener listener)
{
     try
     {
         TcpClient client;
         while (true)
         {
             try
             {
                 client = listener.AcceptTcpClient();
                 //extract data and doing some task
             }
             catch (Exception ex)
             {
                 //Doing some task
             }
         }
      }
      catch (Exception ex)
      {
         //Doing some task
      }
}

The problem I'm facing is that when I deploy this to IIS and run it for more than 2 hours, the thread is killed, and no process is listening to the hardware anymore. Is this issue caused by IIS, and are there any solutions to fix it?

I've saved the exception to the database, and all I got is "Thread was being aborted."


Solution

  • The issue you're facing is probably related to how IIS handles application pools and worker processes. IIS recycles application pools periodically, which can cause background threads to be terminated. This is why your long-running thread is being killed after a certain period of time.

    You can adjust the application pool settings in IIS to prevent it from recycling.