I have 2 forms which set tcp connection. I have 2 buttons connect and stop connection. Problem is if I start connection in 1 Form and click cancel in second Form then TCP connection is stopping and throw error. How to fix it?
Code 1 Form:
using NModbus.Device;
using ModBusHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusProfile;
using NModbus;
using NModbus.Utility;
using System.Net;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
code
Assistant
User
Assistant
User
Assistant
BackgroundWorker BackgroundWork = new BackgroundWorker();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
private bool __connection_set;
public ECTStatePageForm(CommanderForm CommanderFormInstance)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
if (ConnectionManager.IsConnectionActive())
{
CurrentConnectionState.ForeColor = Color.OrangeRed;
CurrentConnectionState.Text = "Соединение уже активно в другой вкладке!";
}
}
private void Get_ECT_State_StartButton_Click(object sender, EventArgs e)
{
int modBusPort;
string boardIP;
if (BackgroundWork.IsBusy != true)
{
if (CommanderForm.BoardIPTextBox.Text != "")
{
boardIP = CommanderForm.BoardIPTextBox.Text;
}
else
{
MessageBox.Show("Введите IP адрес устройства.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
// Attempt to retrieve and parse the ModBus port
try
{
modBusPort = int.Parse(CommanderForm.ModBusPortTextBox.Text);
}
catch (FormatException)
{
MessageBox.Show("Неправильный формат номера порта. Пожалуйста введите целое число.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
catch (ArgumentNullException)
{
MessageBox.Show("Введите номер порта ModBus.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CurrentConnectionState.ForeColor = Color.DarkGray;
CurrentConnectionState.Text = "Подключение...";
_connection = ConnectionManager.OpenConnection(boardIP, modBusPort);
__connection_set = true;
}
catch (ArgumentException ex)
{
CurrentConnectionState.ForeColor = Color.Red;
CurrentConnectionState.Text = "Ошибка подключения!";
MessageBox.Show("Ошибка ввода: " + ex.Message);
return;
}
catch (InvalidOperationException ex)
{
CurrentConnectionState.ForeColor = Color.Red;
CurrentConnectionState.Text = "Ошибка подключения!";
MessageBox.Show("Ошибка соединения: " + ex.Message);
return;
}
// Start background work
try
{
CurrentConnectionState.Text = "Подключено!";
CurrentConnectionState.ForeColor = Color.Green;
BackgroundWork.RunWorkerAsync();
}
catch (InvalidOperationException ex)
{
MessageBox.Show($"Невозможно запустить процесс в фоновом режиме: {ex.Message}", "Ошибка запуска процесса", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void Get_ECT_State_CancelButton_Click(object sender, EventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation == true)
{
if (ConnectionManager.IsConnectionActive() && __connection_set)
{
ConnectionManager.CloseConnection();
}
BackgroundWork.CancelAsync();
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (e.Cancel == false)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(_connection.Item2);
ste1TextBox.Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
}));
ste2TextBox.Invoke(new Action(() =>
{
ste2TextBox.Text = espValues.ste[1].ToString();
}));
ste3TextBox.Invoke(new Action(() =>
{
ste3TextBox.Text = espValues.ste[2].ToString();
}));
ste4TextBox.Invoke(new Action(() =>
{
ste4TextBox.Text = espValues.ste[3].ToString();
}));
if (espValues.rms.Length > rmsDataTable.Rows.Count)
{
for (int i = 1; i < espValues.rms.Length; i++)
{
rmsDataGridView.Invoke(new MethodInvoker(() =>
{
rmsDataTable.Rows.Add(new object[] { i, 0 });
}));
}
}
else if (espValues.rms.Length < rmsDataTable.Rows.Count)
{
int current_row = rmsDataTable.Rows.Count - 1;
while (espValues.rms.Length < rmsDataTable.Rows.Count)
{
rmsDataGridView.Invoke(new MethodInvoker(() =>
{
rmsDataTable.Rows[current_row].Delete();
}));
current_row--;
}
}
if (espValues.diaps.Length > diapsDataTable.Rows.Count)
{
for (int i = 1; i < espValues.diaps.Length; i++)
{
diapsDataGridView.Invoke(new MethodInvoker(() =>
{
diapsDataTable.Rows.Add(new object[] { i, 0 });
}));
}
}
else if (espValues.diaps.Length < diapsDataTable.Rows.Count)
{
int current_row = diapsDataTable.Rows.Count - 1;
while (espValues.diaps.Length < diapsDataTable.Rows.Count)
{
diapsDataGridView.Invoke(new MethodInvoker(() =>
{
diapsDataTable.Rows[current_row].Delete();
}));
current_row--;
}
}
for (int k = 0; k < espValues.rms.Length; k++)
{
rmsDataTable.Rows[k][1] = espValues.rms[k];
}
rmsDataGridView.Invoke(new Action(() =>
{
rmsDataGridView.DataSource = rmsDataTable;
}));
for (int z = 0; z < espValues.diaps.Length; z++)
{
diapsDataTable.Rows[z][1] = espValues.diaps[z];
}
diapsDataGridView.Invoke(new Action(() =>
{
diapsDataGridView.DataSource = diapsDataTable;
}));
System.Threading.Thread.Sleep(1000);
}
}
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation == true)
{
if (ConnectionManager.IsConnectionActive() && __connection_set)
{
ConnectionManager.CloseConnection();
}
BackgroundWork.CancelAsync();
}
}
}
}
To address the issue of closing a TCP connection from one form while it might be still in use by another, you can make some architectural improvements to your code. The key is to have a centralized connection management system that allows multiple forms to communicate with each other regarding the connection's state and prevent inadvertent disconnection.
Here's a strategy you can follow alongside necessary modifications:
Step-by-step Improvements
Centralize Connection Management:
Implement a ConnectionManager class as a singleton to manage the TCP connection. This will ensure that the connection is shared across all forms and a single point manages its state.
Track Active Users:
Implement a counter or list in the ConnectionManager to count or list the forms actively using the connection. Increment or add when a form initializes the connection and decrement or remove when a form is closed or cancels the operation.
Close Connection Safely:
Only close the connection if no active users (i.e., forms in this context) are using it. This way, you prevent one form from stopping a connection being used by another form.
Update Your Forms:
Modify event handlers in your forms to interact with the ConnectionManager accordingly.
Example Code Changes
Below are the code snippets for the ConnectionManager class and updated event handlers:
ConnectionManager Class
csharp
public class ConnectionManager
{
private static ConnectionManager _instance;
private static readonly object _lock = new object();
private Tuple<TcpClient, IModbusMaster> _connection;
private int _activeUsers;
private ConnectionManager() { }
public static ConnectionManager Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new ConnectionManager();
}
return _instance;
}
}
}
public bool IsConnectionActive() => _connection != null;
public Tuple<TcpClient, IModbusMaster> OpenConnection(string ip, int port)
{
if (_connection == null)
{
var client = new TcpClient(ip, port);
var factory = new ModbusFactory();
var master = factory.CreateMaster(client);
_connection = Tuple.Create(client, master);
}
_activeUsers++;
return _connection;
}
public void CloseConnection()
{
_activeUsers--;
if (_activeUsers <= 0)
{
_connection.Item1.Close();
_connection = null;
}
}
}
Updates in ECTStatePageForm
csharp
private void Get_ECT_State_StartButton_Click(object sender, EventArgs e)
{
// Attempt to retrieve and parse the ModBus port
if (CommanderForm.BoardIPTextBox.Text == "")
{
MessageBox.Show("Введите IP адрес устройства.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!int.TryParse(CommanderForm.ModBusPortTextBox.Text, out int modBusPort))
{
MessageBox.Show("Неправильный формат номера порта. Пожалуйста введите целое число.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (BackgroundWork.IsBusy != true)
{
try
{
CurrentConnectionState.ForeColor = Color.DarkGray;
CurrentConnectionState.Text = "Подключение...";
_connection = ConnectionManager.Instance.OpenConnection(CommanderForm.BoardIPTextBox.Text, modBusPort);
CurrentConnectionState.Text = "Подключено!";
CurrentConnectionState.ForeColor = Color.Green;
BackgroundWork.RunWorkerAsync();
}
catch (Exception ex)
{
CurrentConnectionState.ForeColor = Color.Red;
CurrentConnectionState.Text = $"Ошибка подключения: {ex.Message}";
}
}
}
private void Get_ECT_State_CancelButton_Click(object sender, EventArgs e)
{
BackgroundWork.CancelAsync();
ConnectionManager.Instance.CloseConnection();
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
BackgroundWork.CancelAsync();
ConnectionManager.Instance.CloseConnection();
}
These changes ensure the connection is not unintentionally closed by another form, providing a more robust connection management system. Adjust the code accordingly for your specific implementation details.
I already have ConnectionManager class, fix it with your changes.
Code:
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Windows.Forms;
using System.Net.Http;
namespace Configurator
{
public class ConnectionManager
{
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
code
private static Tuple<TcpClient, IModbusMaster> _connection;
// Метод для открытия соединения
public static Tuple<TcpClient, IModbusMaster> OpenConnection(string ipAddress, int modBusPort)
{
if (_connection != null)
{
throw new InvalidOperationException("Соединение уже открыто.");
}
// Проверка IP-адреса
if (!IsValidIpAddress(ipAddress))
{
throw new ArgumentException("Некорректный IP-адрес.");
}
// Проверка порта
if (modBusPort < 0 || modBusPort > 65535)
{
throw new ArgumentOutOfRangeException(nameof(modBusPort), "Порт должен быть в диапазоне от 0 до 65535.");
}
try
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ipAddress, modBusPort);
if (tcpClient != null)
{
try
{
var factory = new ModbusFactory();
IModbusMaster modbusMaster = factory.CreateMaster(tcpClient);
_connection = new Tuple<TcpClient, IModbusMaster>(tcpClient, modbusMaster);
return _connection;
}
catch (Exception ex)
{
throw new Exception($"Ошибка создания ModBus соединения: {ex.Message}");
}
}
else
{
throw new Exception($"Ошибка установки TCP соединения.");
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Не удалось установить соединение: " + ex.Message);
}
}
// Метод для закрытия соединения
public static void CloseConnection()
{
if (_connection != null)
{
//_connection.Item2.Dispose();
_connection.Item1.Client.Shutdown(SocketShutdown.Both);
_connection.Item1.Close();
_connection = null;
}
}
// Метод для проверки активного соединения
public static bool IsConnectionActive()
{
return _connection != null;
}
// Метод для проверки корректности IP-адреса
private static bool IsValidIpAddress(string ipAddress)
{
return IPAddress.TryParse(ipAddress, out _);
}
public static int modBusPortValidation(string modBusPort)
{
// Attempt to retrieve and parse the ModBus port
try
{
int processedModBusPort = int.Parse(modBusPort);
return processedModBusPort;
}
catch (FormatException)
{
throw new FormatException("Неправильный формат номера порта. Пожалуйста введите целое число.");
}
catch (ArgumentNullException)
{
throw new ArgumentNullException("Введите номер порта ModBus.");
}
}
}
}
To address the issue of managing the TCP connection across multiple forms without having it accidentally closed, we'll need to make some modifications to your existing ConnectionManager class. We'll introduce a counter to keep track of how many forms are currently using the connection. The connection will only be closed when no forms are using it.
Here's an updated version of your ConnectionManager class with these changes:
csharp
public class ConnectionManager
{
private static Tuple<TcpClient, IModbusMaster> _connection;
private static int _activeForms = 0; // Counter for active forms
private static readonly object _lock = new object(); // To ensure thread safety
// Method to open connection
public static Tuple<TcpClient, IModbusMaster> OpenConnection(string ipAddress, int modBusPort)
{
lock (_lock) // Ensure thread safety
{
// Check if the connection is already opened
if (_connection == null)
{
// Validate IP address and port
ValidateIpAddressAndPort(ipAddress, modBusPort);
// Try to open the connection
var tcpClient = new TcpClient();
tcpClient.Connect(ipAddress, modBusPort);
var factory = new ModbusFactory();
IModbusMaster modbusMaster = factory.CreateMaster(tcpClient);
_connection = Tuple.Create(tcpClient, modbusMaster);
}
// Increase the active form counter
_activeForms++;
return _connection;
}
}
// Method to close connection
public static void CloseConnection()
{
lock (_lock) // Ensure thread safety
{
if (_activeForms > 0)
{
_activeForms--;
if (_activeForms == 0 && _connection != null)
{
// Actual closing logic
_connection.Item1.Client.Shutdown(SocketShutdown.Both);
_connection.Item1.Close();
_connection = null;
}
}
}
}
// Check if there is an active connection
public static bool IsConnectionActive()
{
return _connection != null;
}
// Validate IP address and ModBus port
private static void ValidateIpAddressAndPort(string ipAddress, int modBusPort)
{
if (!IsValidIpAddress(ipAddress))
{
throw new ArgumentException("Некорректный IP-адрес.");
}
if (modBusPort < 0 || modBusPort > 65535)
{
throw new ArgumentOutOfRangeException(nameof(modBusPort), "Порт должен быть в диапазоне от 0 до 65535.");
}
}
// IP address validation
private static bool IsValidIpAddress(string ipAddress)
{
return IPAddress.TryParse(ipAddress, out _);
}
public static int ModBusPortValidation(string modBusPort)
{
try
{
return int.Parse(modBusPort);
}
catch (FormatException)
{
throw new FormatException("Неправильный формат номера порта. Пожалуйста введите целое число.");
}
catch (ArgumentNullException)
{
throw new ArgumentNullException("Введите номер порта ModBus.");
}
}
}
Adjustments in the Form
Here is how you would use the ConnectionManager in your form event handlers:
Not explicitly created here since existing static members ensure a single connection manager.
Thread Safety:
Added _lock to synchronize access to shared resources.
Reference Counting:
_activeForms tracks the number of forms using the connection. This ensures the connection is only closed when no forms are actively using it.
These changes will help manage the connection more effectively and avoid premature disconnection by one of the forms.
Fix another form which can open connection.
Code:
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Configurator
{
public partial class SWRCTStatePageForm : Form
{
CommanderForm CommanderForm;
To ensure that your SWRCTStatePageForm works correctly with the updated ConnectionManager, you need to make sure that it handles the connection logic consistently and safely. Specifically, it should correctly manage the connection lifecycle using the connection manager's reference counting approach. Here's an updated version of your SWRCTStatePageForm that incorporates these practices:
Updated SWRCTStatePageForm
csharp
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Data;
using System.Drawing;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Configurator
{
public partial class SWRCTStatePageForm : Form
{
private CommanderForm CommanderForm;
private BackgroundWorker BackgroundWork = new BackgroundWorker();
private DataTable cntvDataTable = new DataTable();
private ModBusProfile ModBusProfileHelper = new ModBusProfile();
private ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
private ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
private bool __connection_set;
public SWRCTStatePageForm(CommanderForm CommanderFormInstance)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
InitializeTableWithDefaults();
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
}
private void InitializeTableWithDefaults()
{
ModBusProfile.ssp ssp = ExporterLinkerHelper.ssp_Default;
ste1TextBox.Text = ssp.ste[0].ToString();
ste2TextBox.Text = ssp.ste[1].ToString();
ste3TextBox.Text = ssp.ste[2].ToString();
ste4TextBox.Text = ssp.ste[3].ToString();
cntvDataTable.Columns.Add("Канал", typeof(int));
cntvDataTable.Columns.Add("Накопленное значение расхода ресурса (%)", typeof(float));
cntvDataTable.Columns.Add("Количество отключений", typeof(ushort));
cntvDataTable.Columns.Add("Количество включений", typeof(ushort));
cntvDataTable.Rows.Add(new object[] { 0, ssp.cntv[0].Racc, ssp.cntv[0].ofcnt, ssp.cntv[0].oNacnt });
cntvDataGridView.DataSource = cntvDataTable;
}
private void Get_SWRCT_State_StartButton_Click(object sender, EventArgs e)
{
if (!BackgroundWork.IsBusy)
{
try
{
string boardIP = GetBoardIP();
int modBusPort = GetModBusPort();
_connection = ConnectionManager.OpenConnection(boardIP, modBusPort);
__connection_set = true;
BackgroundWork.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private string GetBoardIP()
{
if (string.IsNullOrWhiteSpace(CommanderForm.BoardIPTextBox.Text))
{
throw new ArgumentException("Введите IP адрес устройства.");
}
return CommanderForm.BoardIPTextBox.Text;
}
private int GetModBusPort()
{
try
{
return int.Parse(CommanderForm.ModBusPortTextBox.Text);
}
catch (FormatException)
{
throw new FormatException("Неправильный формат номера порта. Пожалуйста введите целое число.");
}
catch (ArgumentNullException)
{
throw new ArgumentNullException("Введите номер порта ModBus.");
}
}
private void Get_SWRCT_State_CancelButton_Click(object sender, EventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
if (__connection_set)
{
ConnectionManager.CloseConnection();
}
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
while (!e.Cancel)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
UpdateDataFromConnection();
System.Threading.Thread.Sleep(1000);
}
}
private void UpdateDataFromConnection()
{
ModBusProfile.ssp sspValues = ModBusProfileHelper.swrct_state_page_Read(_connection.Item2);
UpdateTextBoxSafely(ste1TextBox, sspValues.ste[0].ToString());
UpdateTextBoxSafely(ste2TextBox, sspValues.ste[1].ToString());
UpdateTextBoxSafely(ste3TextBox, sspValues.ste[2].ToString());
UpdateTextBoxSafely(ste4TextBox, sspValues.ste[3].ToString());
// Update cntvDataTable here similarly...
Invoke(new Action(() => cntvDataGridView.DataSource = cntvDataTable));
}
private void UpdateTextBoxSafely(TextBox textBox, string value)
{
textBox.Invoke(new Action(() => textBox.Text = value));
}
private void SWRCTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
if (__connection_set)
{
ConnectionManager.CloseConnection();
}
}
}
}
}
Key Changes and Considerations:
Centralized Error Handling:
Moved IP and port retrieval to separate methods with exception handling.
Connection Logic:
The connection is only closed if __connection_set is true, which ensures that this form actually opened the connection.
Use ConnectionManager.CloseConnection() inside Get_SWRCT_State_CancelButton_Click and FormClosing to properly manage the connection lifecycle.
Thread Safety and Responsiveness:
Use Invoke to safely update UI elements from the background worker.
Background Worker:
The loop in BackgroundWork_DoWork method is simplified to ensure proper checking for cancellation.
These changes ensure that your forms interact with the ConnectionManager correctly and maintain consistent connection management across multiple forms. Each form only opens a connection when needed and closes it correctly when no longer in use.