将事件添加到对象&处理它
我有一个内存流对象,它将在特定的时间间隔内更新。
当内存流对象发生更新时,应该创建并更新该事件。提出。 然后应该有一个事件处理程序来处理引发的事件。
请建议任何代码或示例以供参考。
提前致谢。
I have a memorystream object which is to be updated a particular time interval.
When a update occurs on the memorystream object the event should be created & raised.
Then there should be a event handler to handle the raised event.
Please suggest any code or sample for ref.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你知道事件的逻辑吗?
如果是这样,请在将更新内存流的类中创建一个事件。
更新时,引发事件。
在类的消费者处注册事件。
基本上就是这样?
也许你的疑问是一般事件。为此,我建议您阅读 MSDN,例如
Do you know event's logic at all?
If so, Create an event in the class where your memory stream will be updated.
When updating it, raise the event.
At the class' consumer register the event.
And, basically, that's it?
Maybe your doubt are events in general. For that i'd suggest you to read MSDN, e.g.
有几种方法可以解决这个问题。
最简单的方法是刚刚击败我的人建议的方法,而不是直接调用 MemoryStream.Write(),而是在应用程序中编写一个调用 MemoryStream.Write() 的方法,然后调用您自己声明的事件在 MemoryStream 对象之外。
在更奇特但更简洁的角落,您可以大胆地从 MemoryStream 继承一个类,在其中添加事件属性并重写 Write() 方法(或您调用来进行写入的任何方法)以调用基类类 Write() 方法,然后引发事件。有些人可能会采用这种方法,根据您使用 MemoryStream 的方式,它可能不太理想或有问题,但它会完成您想要的工作,并且使您不必在每次编写时自己引发事件。
There are a couple ways you could go about this.
The easiest way would be that suggested by the guy that just beat me to the punch and instead of calling MemoryStream.Write() directly, write a method in your application that invokes MemoryStream.Write() and then invokes an event that you declare yourself outside the MemoryStream objeect.
In the more exotic but more concise corner, you could be daring and inherit a class from MemoryStream where you add an event property and override the Write() method (or whichever method(s) you call to do the writing) to invoke the base class Write() method and then raise the event. Some may pupu this approach and it could be less than ideal or problematic depending on how you are using MemoryStream, but it would do the job you want and keep you from having to raise the event yourself every time you write.
有关注册和引发自定义事件的好示例可以在 http: //www.switchonthecode.com/tutorials/csharp-snippet-tutorial-custom-event-handlers
更新:链接已损坏,我使用了 archive.org 从那里引用(更改事件引发部分以避免竞争条件):
A good sample about registering and raising custom events can be found at http://www.switchonthecode.com/tutorials/csharp-snippet-tutorial-custom-event-handlers
Update: The link is broken, I used archive.org to quote from there (Changed event raising part to avoid race condition):