Search code examples
c#labview

Should a NI LabVIEW NetworkVariableManager be left connected?


I've received some C# code from a colleague for interacting with a cRIO device connected over ethernet. I'm trying to improve the code quality to make it a bit more comprehensible for future users, however I'm struggling a little bit to extract some relevant information from the API documentation. My main question is whether there would be problems caused in leaving a NetworkVariableManager in the Connected state?

Right now the code uses a class which looks something like

public class RIOVar<T>
{
    public readonly string location;

    public RIOVar(string location)
    {
        this.location = location;
    }

    public T Get()
    {
        using(NetworkVariableReader<T> reader = new NetworkVariableReader<T>(location) )
        {
            reader.Connect();
            return reader.ReadData().GetValue()
        }
    }

    public void Write(T value)
    {
        using(NetworkVariableWriter<T> writer = new NetworkVariableWriter<T>(location) )
        {
            writer.Connect();
            writer.WriteValue(value);
        }
    }
}

The actual class does a lot more than this, but the part that actually communicates with the cRIO basically boils down to these two methods and the location data member.

What I'm wondering about is whether it would be better to instead have reader and writer as class members and Connect them in the constructor (at the point that they are constructed the connection should be posible), but what I don't know is if this would have some adverse effect on the way the computer and RIO communicate with each other (maybe a connected manager uses some resource or the program must maintain some sort of register...?) and therefore the approach here of having the manager connected only for the read/write operation is better design.


Solution

  • Keeping a variable connected keeps its backing resources in memory:

    • threads
    • sockets
    • data buffers

    These resources are listed in the online help, but it's unclear to me if that list is complete:

    • NationalInstruments.NetworkVariable uses multiple threads to implement the reading and writing infrastructure. When reading or writing in a tight loop insert a Sleep call, passing 0, to allow a context switch to occur thereby giving the network variable threads time to execute.
    • ... snip ...
    • NationalInstruments.NetworkVariable shares resources such as sockets and data buffers among connections that refer to the same network variable in the same program.

    In my opinion, I'd expect better runtime performance by connecting/disconnecting as infrequently as possible. For example, when the network is reachable, connect; when it isn't, disconnect.