RAPI Approach: 1 static instance for the entire winforms app vs create,connect,dispose

246 views Asked by At

In many places in our application we have code like this:

using(RAPI rapi = new RAPI())
{
  bool connected = TryToConnectWithTimeout(rapi);
  if(connected)
    DoSomethingWithRapi(rapi);
}

This has worked well so far. We never have more than 1 rapi instance at a time. Until now:

But now we want to listen for the connect event on rapi. We are doing it like this:

void StartMonitoringRapiConnection()
{
_rapi = new RAPI();
_rapi.RAPIConnected += new RAPIConnectedHandler(_rapi_RAPIConnected);
_rapi.RAPIDisconnected += new RAPIConnectedHandler(_rapi_RAPIDisconnected);
_rapi.Connect(false,-1);
}

    private void _rapi_RAPIConnected()
    {
    DoWorkWhenRapiConnects();
    }
    private void _rapi_RAPIDisconnected()
    {
        //Listen for the next time that rapi connects
        _rapi.Connect(false,-1);
        DoWorkWhenRapiDisconnects();
    }

"StartMonitoringRapiConnection" works pretty well as long as I do not start to new up and connect other RAPI objects. But once I start newing up other RAPI objects, the connect/disconnect events seem to fire out of order.

Would it work better to have just 1 static instance of RAPI for the entire app? Do you have any other advice? Thanks.

1

There are 1 answers

1
ctacke On BEST ANSWER

Logically, RAPI is a single connection between the PC and the device. It doesn't make sense for your app to even support multiple connections. I'd make a Singleton class that wraps up the RAPI calls and makes all of your calls for you so that everyone that needs to talk to the device goes through that one class.