RAPI 方法:整个 winforms 应用程序的 1 个静态实例与创建、连接、处置
在我们的应用程序的许多地方,我们都有这样的代码:
using(RAPI rapi = new RAPI())
{
bool connected = TryToConnectWithTimeout(rapi);
if(connected)
DoSomethingWithRapi(rapi);
}
到目前为止,这运行良好。 我们一次不会有超过 1 个 Rapi 实例。到目前为止:
但现在我们想监听 RAPI 上的连接事件。 我们这样做是这样的:
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();
}
只要我不开始新建并连接其他 RAPI 对象,“StartMonitoringRapiConnection”就可以很好地工作。但是,一旦我开始更新其他 RAPI 对象,连接/断开事件似乎就会乱序触发。
整个应用程序只有 1 个静态 RAPI 实例会更好吗?您还有其他建议吗?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从逻辑上讲,RAPI 是 PC 和设备之间的单一连接。您的应用程序支持多个连接是没有意义的。我会创建一个 Singleton 类 来包装 RAPI 调用并为您进行所有呼叫,以便每个需要与设备通话的人都可以完成这一类。
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.