code_junkie

Problem disposing of socket / finalising twice?

Nov 13th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. public class Foo
  2. {
  3. private Socket sock = null;
  4. private Thread tListenerThread = null
  5. private bool bInitialised;
  6. private Object InitLock = null;
  7. private Object DeInitLock = null;
  8.  
  9. public Foo()
  10. {
  11. bInitialised = false;
  12.  
  13. InitLock = new Object();
  14. DeInitLock = new Object();
  15. }
  16.  
  17. public bool initialise()
  18. {
  19. if (null == InitLock)
  20. return false;
  21.  
  22. lock (InitLock)
  23. {
  24. if (bInitialised)
  25. return false;
  26.  
  27. sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  28. sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 8);
  29. sock.Bind( /*localIpEndPoint*/);
  30. sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(mcIP));
  31.  
  32. tListenerThread = new Thread(new ThreadStart(listener));
  33. tListenerThread.Start();
  34.  
  35. bInitialised = true;
  36. return true;
  37. }
  38. }
  39.  
  40. ~Foo()
  41. {
  42. if (bInitialised)
  43. deInitialise();
  44. }
  45.  
  46. private void deInitialise()
  47. {
  48. if (null == DeInitLock)
  49. return;
  50.  
  51. lock (DeInitLock)
  52. {
  53. if (bInitialised)
  54. {
  55. sock.Shutdown(SocketShutdown.Both); //throws System.ObjectDisposedException
  56. sock.Close();
  57.  
  58. tListenerThread.Abort(); //terminates xunit test!
  59. tListenerThread = null;
  60.  
  61. sock = null;
  62.  
  63. bInitialised = false;
  64. }
  65. }
  66. }
  67. }
Add Comment
Please, Sign In to add comment