A więc tak.
NetworkInterface.GetIsNetworkAvailable
sprawdza czy jakiekolwiek połączenie jest aktywne. Z dokumentacji:
Indicates whether any network connection is available.
link
Więc to nie zadziała w sytuacji jeżeli będziesz miał więcej niż 1 kartę sieciową aktywną, bo sprawdza czy jakiekolwiek połączenie jest dostępne.
Żeby uprościc kod możesz zasubskrybować się na zdarzenie NetworkAvailabilityChanged
link. To zdarzenie pod spodem jest oparte o metodę NetworkInterface.GetIsNetworkAvailable
więc zrobi to co ty teraz robisz tylko bez tego spaghetti bo wystarczy sobie napisać pod to zdarzenie handler NetworkAvailabilityChangedEventHandler
link
Do sprawdzania stanu połączenia mógłbyś też użyć klasy TcpConnectionInformation
. Z dokumentacji:
Provides information about the Transmission Control Protocol (TCP) connections on the local computer.
link
Klasa zwraca obiekt TcpConnectionInformation
który zawiera property State
która jest enumem TcpState
i wartość enuma wskazuje na stan protokołu TCP
Specifies the states of a Transmission Control Protocol (TCP) connection.
link
Wartości enuma:
Closed 1
The TCP connection is closed.
CloseWait 8
The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing 9
The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
DeleteTcb 12
The transmission control buffer (TCB) for the TCP connection is being deleted.
Established 5
The TCP handshake is complete. The connection has been established and data can be sent.
FinWait1 6
The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
FinWait2 7
The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
LastAck 10
The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen 2
The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
SynReceived 4
The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
SynSent 3
The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
TimeWait 11
The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown 0
The TCP connection state is unknown.