I have a form CommanderForm which open and closes TCP connection and open SWRCTStatePageForm. If I firstly open SWRCTStatePageForm and then open TCP connection in CommanderForm and after that close SWRCTStatePageForm i get an error: "System.ObjectDisposedException: "Доступ к ликвидированному объекту невозможен." in line: Invoke(new Action(() =>
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
How to fix it?
Code:
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Data;
using System.Net.Sockets;
using System.Windows.Forms;
using System.ComponentModel;
namespace Configurator
{
public partial class SWRCTStatePageForm : Form
{
CommanderForm CommanderForm;
private BackgroundWorker BackgroundWork = new BackgroundWorker();
private DataTable cntvDataTable = new DataTable();
code
Assistant
User
Write full code of the SWRCTStatePageForm with these fixes.
The issue you are encountering with the "System.ObjectDisposedException" is happening because the form (SWRCTStatePageForm) is closed, and you're attempting to invoke a method (Invoke() for UI updates) on a disposed object. Here are the steps and changes you can implement to address this problem:
Steps to address the ObjectDisposedException:
Check if Form is Disposed before Invoke:
Before calling Invoke, you can check if the form is not disposed. You can accomplish this by adding a check inside your BackgroundWork_DoWork method.
It might be a good practice to enclose an Invoke call within a conditional check for InvokeRequired to make sure you're invoking actions on the UI thread safely.
csharp
if (!this.IsDisposed && InvokeRequired)
{
Invoke(new Action(() => // Your UI updating code here ));
}
else if (!this.IsDisposed)
{
// Direct method call if Invoke is not required
}
Handle Worker Cancellation & Form Disposal Safely:
Ensure that when you're closing the form, you properly handle cancellation of the BackgroundWorker and ensure that it has completed its pending operations.
csharp
private void SWRCTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.IsBusy)
{
BackgroundWork.CancelAsync();
// Optionally wait for the worker to actually cancel
while (BackgroundWork.IsBusy)
{
Application.DoEvents(); // Pump messages to keep the UI responsive
}
}
CommanderForm.ConnectionStarted -= OnConnectionStarted;
CommanderForm.ConnectionStopped -= OnConnectionStopped;
}
Additional Considerations:
Ensure Background Work Ends Gracefully:
Make sure any ongoing background operations are gracefully stopped via the cancellation mechanism before you actually send the form into a close/dispose state.
Logging and Debugging:
Adding logging or debugging messages to verify the state of your application parts (like checking dispose status) can help identify where exactly the problem occurs.
These approaches should help in ensuring that you avoid trying to access UI elements of a disposed form instance and stop encountering the ObjectDisposedException. By managing both the form's state and the lifecycle of background operations, you can improve the robustness of your application.
Certainly! Below is the complete code for the SWRCTStatePageForm class with the necessary fixes to handle the ObjectDisposedException. I have implemented checks to ensure that the form is not disposed before invoking any UI-related methods, handled worker cancellation, and ensured the UI is updated safely.
csharp
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Data;
using System.Net.Sockets;
using System.Windows.Forms;
using System.ComponentModel;
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 ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
public SWRCTStatePageForm(CommanderForm CommanderFormInstance)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
// Subscribe to events from the CommanderForm
CommanderForm.ConnectionStarted += OnConnectionStarted;
CommanderForm.ConnectionStopped += OnConnectionStopped;
InitializeDataTable();
InitializeBackgroundWorker();
// Check if the connection is already active
var existingConnection = CommanderForm.GetCurrentConnection();
if (existingConnection != null && existingConnection.Item1.Connected)
{
OnConnectionStarted(existingConnection);
}
}
private void InitializeDataTable()
{
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 InitializeBackgroundWorker()
{
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += BackgroundWork_DoWork;
}
private void OnConnectionStarted(Tuple<TcpClient, IModbusMaster> connection)
{
_connection = connection;
if (!BackgroundWork.IsBusy)
{
BackgroundWork.RunWorkerAsync(argument: _connection);
}
}
private void OnConnectionStopped()
{
if (BackgroundWork.IsBusy)
{
BackgroundWork.CancelAsync();
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
SafeInvoke(() =>
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
);
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
try
{
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
ModBusProfile.ssp sspValues = ModBusProfileHelper.swrct_state_page_Read(modbusMaster);
SafeInvoke(() =>
{
ste1TextBox.Text = sspValues.ste[0].ToString();
ste2TextBox.Text = sspValues.ste[1].ToString();
ste3TextBox.Text = sspValues.ste[2].ToString();
ste4TextBox.Text = sspValues.ste[3].ToString();
UpdateCntvDataTable(sspValues);
});
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception ex)
{
SafeInvoke(() =>
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
);
}
}
private void SafeInvoke(Action action)
{
if (!this.IsDisposed && !this.Disposing)
{
if (InvokeRequired)
{
Invoke(action);
}
else
{
action();
}
}
}
private void UpdateCntvDataTable(ModBusProfile.ssp sspValues)
{
while (sspValues.cntv.Length > cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.Add(new object[] { cntvDataTable.Rows.Count, 0, 0, 0 });
}
while (sspValues.cntv.Length < cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.RemoveAt(cntvDataTable.Rows.Count - 1);
}
for (int z = 0; z < sspValues.cntv.Length; z++)
{
cntvDataTable.Rows[z][1] = sspValues.cntv[z].Racc;
cntvDataTable.Rows[z][2] = sspValues.cntv[z].ofcnt;
cntvDataTable.Rows[z][3] = sspValues.cntv[z].oNacnt;
}
cntvDataGridView.DataSource = cntvDataTable;
}
private void SWRCTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.IsBusy)
{
BackgroundWork.CancelAsync();
while (BackgroundWork.IsBusy)
{
Application.DoEvents(); // Keep UI responsive
}
}
CommanderForm.ConnectionStarted -= OnConnectionStarted;
CommanderForm.ConnectionStopped -= OnConnectionStopped;
}
}
}
Key Changes:
SafeInvoke: Added a helper method SafeInvoke that checks if the form is in a non-disposed state before attempting to update the UI using Invoke or directly.
FormClosing Handling: Improved form closing logic to ensure that the background worker is properly canceled and stays safe when the form is closed.
DataTable and Modbus Logic: Remain handled in existing ways but protected by the SafeInvoke mechanism to protect against disposed invocation.
This should help ensure that UI-related operations are only executed when the form is valid, thus avoiding ObjectDisposedException.