Matthias R.
Matthias R.

Reputation: 451

Aborting thread + socket connection

I have a (very basic understandig, as i think) question on threading and aborting these:

Situation is: I have an open socket connection in a thread working - now I am aborting the thread by thread.Abort().

Question is: what happens to the socket connection? Will it be closed and disposed? Or do I have to take care of this by myself?

Appendix:

Threads are created here:

foreach (Pcd pcd in LstPcds)
        {
           Thread.Sleep(delay);
           Thread thread = new Thread(pcd.Simulate);
           _lstActiveThreads.Add(thread);
           thread.IsBackground = true;
           thread.Name = pcd.ToString();
           thread.Start();
           count++;
        }

and should be disposed/aborted/whatever here:

  public void DisposePcds()
  {
     try
     {
        foreach (Thread thread in _lstActiveThreads)
        {
           thread.Abort();
        }
     }
     catch (Exception exception)
     {
        MessageBox.Show(exception.ToString());
     }
  }

Each thread has an open Socket connection as shown here:

// connecting (async) to the service
// blocks the thread until connection is established
ConnectionSocket = new Socket(_ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ConnectionSocket.BeginConnect(_ipEndPoint, ConnectCallback, ConnectionSocket);
_manualConnectEvent.WaitOne();

// begin receive data from the server
ReceiveDto receive = new ReceiveDto { Socket = ConnectionSocket };
ConnectionSocket.BeginReceive(receive.Buffer, 0, ReceiveDto.GetBufferSize(), 0, ReceiveCallback, receive);

plus a Timer and its elapsed event where each Socket sends a byte array:

byte[] request = GetRegisterRequestCommand(bank);
ConnectionSocket.Send(request, SocketFlags.None);

Upvotes: 0

Views: 932

Answers (1)

Aron
Aron

Reputation: 15772

Just read the MSDN documentation on the subject.

Firstly. NO your code could never ever work. Disposables need to be either explicitly call .Dispose() on them OR they are called implicitly via the syntactical sugar of using(IDisposable){}.

Now looking at the ThreadAbortException you are able to catch exceptions (but it gets rethrown). So using (which is transformed by the compiler to try{}finally{Dispose()}) will work.

But you have no exception handling.

Upvotes: 1

Related Questions