my current implementation contains a public propriety that is binded to a toggle button
{
get => _isListening;
private set
{
if (_isListening != value)
{
_isListening = value;
OnIsListeningChanged?.Invoke(_isListening);
}
}
}
when the connection starts the IsListening is set to True
public static async Task StartListeningAsync()
{
if (IsListening) return;
IsListening = true;
cancellationTokenSource = new CancellationTokenSource();
var serverAddress = Settings.Default.tcpIpAddr ?? "10.23.5.181";
if (!int.TryParse(Settings.Default.tcpIpPort, out var port))
{
throw new InvalidOperationException("Port is not configured correctly.");
}
InitializeChannel();
using (var tcpClient = new TcpClient())
{
try
{
await tcpClient.ConnectAsync(serverAddress, port);
Debug.WriteLine($"TCP CLIENT IS CONNECTED TO {serverAddress} PORT {port}");
\this is a producer consumer pattern to treat the received messages from the server.
var networkStreamTask = ProcessNetworkStreamAsync(tcpClient, cancellationTokenSource.Token);
var backgroundTask = Task.Run(() => ProcessQueueAsync(cancellationTokenSource.Token), cancellationTokenSource.Token);
await Task.WhenAll(networkStreamTask, backgroundTask);
}
catch (SocketException ex)
{
Debug.WriteLine($"SocketException: {ex.Message}");
MessageBox.Show($"The server refused the connection. Make sure that IP {serverAddress} and port {port} are correct.");
}
catch (OperationCanceledException)
{
Debug.WriteLine("Operation was canceled.");
}
catch (Exception ex)
{
Debug.WriteLine($"Error during startup: {ex.Message}");
MessageBox.Show($"Error during startup: {ex.Message}");
}
finally
{
IsListening = false;
await StopListeningAsync();
FinalizeChannel();
}
}
when the cancellation token is passed the StopListeningAsync turn the isListening back to False.
this implementation sometimes have some bugs that I am not really able to isolate. for example sometimes the incoming messages from the server are stopped and no exception is recorded.
is there a way to keep track of the actual status of the connection to the server and bind it to my control in the UI?