rossmann-engineering / EasyModbusTCP.NET

Modbus TCP, Modbus UDP and Modbus RTU client/server library for .NET implementations
922 stars 396 forks source link

Object reference not set to an instance of an object #101

Closed akbarali2019 closed 1 year ago

akbarali2019 commented 1 year ago

I have implemented EasyModbus library in .NET 6 to get data from several sensors. But the program is shutting down frequently cause of this ERROR. ERRORObject reference not set to an instance of an object. at System.IO.Ports.SerialStream.EventLoopRunner.CallReceiveEvents(Object state) at System.Threading.QueueUserWorkItemCallback.Execute() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()

I am not sure what is the source of this termination. Anyone can help?

Padanian commented 1 year ago

This exception is thrown when you try to access a member that holds a null reference. You are referring to an object that does not exist or that it was deleted or cleaned up in the meantime. I assume you initialised an instance of a class to a variable, but never assigned a default value to it.

akbarali2019 commented 1 year ago

I have written a logic to ensure modbusClient is not null before reading data from the available sensors, and handled possible exceptions in case of it is null.

        try
        {
            // Attempt to create and connect the Modbus client
            modbusClient = CreateAndConnectClient(comPort, baudrate, unitIdentifier);

            // Check if the client was successfully created and connected
            if (modbusClient != null)
            {
                var data = modbusClient.ReadInputRegisters(startAddress, quantity) ?? new int[quantity];
                return data;
            }
            else
            {
                // Handle the case when CreateAndConnectClient returns null
                // Return a new empty integer array
                return new int[quantity];
            }

        }
        catch (Exception ex)
        {
            // Handle any exceptions that occur during reading input registers
            // Return a new empty integer array
            Trace.WriteLine(ex.Message);
            return new int[quantity];
        }