Should I Use Events?

后端 未结 2 451
名媛妹妹
名媛妹妹 2021-01-15 17:57

Hi everyone I need a advice, I\'m developing a desktop application (Winform) using C#, I have a Form and I have a separated class named OPC (other file)

This is s

相关标签:
2条回答
  • 2021-01-15 18:10

    If you are asking whether to use events or whether to just directly call into something, it depends on your use case. Events are a great way to broadcast an action. If more than one item needs to know about something changing using events can decouple your code. That said, if you only care about telling one other piece of code then you can do that too. Events are dispatched on the same thread, so whether you directly call into the subscriber or dispatch it with an event, the executing code is handled in the same context.

    Personally I like to use events to prevent hard coupling. Your dispatcher code doesn't need to know who is subscribing on it. It just says "hey, stuff happened, now you do work".

    Events are also neat because you can combine them with Rx to get sampling and throttling and do all sorts of other cool stuff.

    If you find you are adding a bunch of extra code to propagate that "something happened", you should use an event.

    0 讨论(0)
  • 2021-01-15 18:18

    There are two ways to get data from an OPC server: read directly or use the DataChange event. the choice is up to you and one or the other cannot be described as "best practice". If your question is just about implementation then I can tell you that you're missing " Handles ConnectedGroup.DataChange " on the end of your ConnectedOPCGroup_DataChange sub. Your OPCAutomation library will generate the event, you just have to handle it.

    To address the second part of your question, it would be best practice to have your OPC client class separate from your main form.

    0 讨论(0)
提交回复
热议问题