我有一個Windows窗體中執行tcp/IP套接字連接並保持連接打開的私人對象變量。避免重複調用勝利表單中多個線程的例程?
在form_load上,此對象被初始化,並且表單中有15-20個線程持續運行,它可以訪問此對象。有些情況下Tcp/Ip連接可能會丟失。因此,每當我發現連接丟失時,我都會在線程中調用ReconnectToSocket()方法。我正在執行下面的代碼以確保ReconnectToSocket()方法僅通過使用_ReconnectingSocket屬性被調用一次。但在檢查文本日誌文件後,我發現這個方法在每個子線程中被調用。
如何確保只調用一次此方法並避免重複調用。
以下是我的代碼。我對任何其他方法感興趣,因爲我覺得這不是正確的做法。
bool _bReconnectingSocket = false;//To check if it is currently reconnecting
readonly object lock_reconnectSocket = new object();
private bool _ReconnectingSocket
{
get
{
lock (lock_reconnectSocket)
{
return this._bReconnectingSocket;
}
}
set
{
lock (lock_reconnectSocket)
{
this._bReconnectingSocket = value;
}
}
}
private void ReconnectToSocket()
{
if (!this._ReconnectingSocket)
{
this._ReconnectingSocket = true;
//Each sub thread checks for this variable while looping and exits from the infinite loop
this._Stop = true;
//Join all the Sub Threads Before Reconnecting
foreach (SocketThread thrd in this._subThreadCol)
{
try
{
this._objLog.WriteInfo(string.Format("Joining Subthread - {0} for Reconnecting.", thrd.ThrdID));
thrd.Join();
}
catch { }
}
this.ConnectSocket();
this._ReconnectingSocket = false;
this._Stop = false;
}
}
這看起來很腥。您不能隱藏連接丟失到主動傳輸數據的線程的事實。傳輸無法完成,必須重新啓動。有些事故對於解決問題太有影響。使用15個線程在這裏沒有多大意義。線程爲您購買更多的CPU週期,它不會使線路另一端的機器更快。 –