title: c# detecting disconnect from server with timer
body: <p>I have a client type application that is receiving packets from remote server.
  Now and then it so happens that for some reason server disconnects me.
  Sometimes there are some problems on my end ISP drops internet etc.</p>
  
  <p>I have been trying to catch those exceptions and goog-ling for an answer but at the end every one
  points to "make a timer and check periodically for received packets."</p>
  
  <p>Now i have a function that is receiving all incoming traffic.
  This function is executed every time packet is received.</p>
  
  <p>Now my idea is to create a function that will create timer with let say 50 seconds time out.
  This function will reset timer to 0 each time packet is received and restart it.</p>
  
  <p>If timer reach 50 seconds it will throw an error "disconnected!" and some logic will follow
  how to reconnect.</p>
  
  <p>Now main problem i have is ... i can not "pause" my main packet receiving function. 
  I have tried to make it in another thread but program keep recreating new threads , killing threads by ID is a bad practice and i haven't gone down that road ... yet.</p>
  
  <p>Is this a how i should handle my problem or someone has a better idea?
  Below is my packet receive function.</p>
  
  <pre><code> public void OnReceive()
          {
             try
              {
                 recv_pack = locSec.TrIncom();
                  if (recv_pack != null)
                  {
                      foreach (Packet packet in recv_pack)
                      {                     
                          byte[] packet_bytes = packet.GetBytes();
  
                          PacketHandler.HandlePacket(packet, locSec);
                          //here i would check for packet receive with timer                  
                          //CheckDisconnect();
                      }
                  }
              }
              catch() 
              {}
          }
  </code></pre>
  
  <p>So far i have come up with this:</p>
  
  <pre><code>public bool CheckDisconnect()
  {
      bool KeepGoing = true;
  
      for(int i = 0 ; i &lt;= 50 &amp;&amp; KeepGoing; i++ )
      {
          Thead.Sleep(1000);
  
          if(i == 50)
          {
              KeepGoing = false;
              Console.WriteLine("Disconnected!");
              // ... starting reconnect procedure
          }
      }
  }
  </code></pre>