我有一個(非常基本的understandig,因爲我認爲)的線程問題和中止這些:中止線程+插座連接
的情況是:我有一個線程工作的開放套接字連接 - 我現在中止線由thread.Abort()
。
問題是:套接字連接會發生什麼?它會被關閉和處置嗎?還是我必須自己照顧這個?
附錄:
線程是這裏創建:
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++;
}
,應設置/中止/不管這裏:
public void DisposePcds()
{
try
{
foreach (Thread thread in _lstActiveThreads)
{
thread.Abort();
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
每個thread
具有敞開Socket
連接,如下所示:
// 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);
加上定時器並且其中每個Socket
發送一個字節數組其經過事件:
byte[] request = GetRegisterRequestCommand(bank);
ConnectionSocket.Send(request, SocketFlags.None);
切勿使用'Thread.Abort()'。真。很少有任何有效的理由來使用它。你應該使用一種機制(比如'AutoResetEvent'等)來允許線程正常關閉。 –
你能告訴我們零件嗎?在哪裏放棄線程並關閉連接? – Max
套接字連接將不會自動關閉。你必須手動完成。顯示代碼有助於我們確定:) –