SocketUtils.cs 963 B

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. namespace Utilities
  7. {
  8. public class SocketUtils
  9. {
  10. /// <summary>
  11. /// Socket will be forcefully closed, all pending data will be ignored, and socket will be deallocated.
  12. /// </summary>
  13. public static void ReleaseSocket(Socket socket)
  14. {
  15. if (socket != null)
  16. {
  17. if (socket.Connected)
  18. {
  19. socket.Shutdown(SocketShutdown.Both);
  20. try
  21. {
  22. socket.Disconnect(false);
  23. }
  24. catch (SocketException)
  25. { }
  26. }
  27. socket.Close();
  28. socket = null;
  29. GC.Collect();
  30. GC.WaitForPendingFinalizers();
  31. }
  32. }
  33. }
  34. }