usr021986
usr021986

Reputation: 3511

Add an event to a object & handle it

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.

Upvotes: 0

Views: 3112

Answers (3)

Kamyar
Kamyar

Reputation: 18797

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):

using System;

namespace CustomEvents
{
  public class Car
  {
    public delegate void OwnerChangedEventHandler(string newOwner);
    public event OwnerChangedEventHandler OwnerChanged;

    private string make;
    private string model;
    private int year;
    private string owner;

    public string CarMake
    {
      get { return this.make; }
      set { this.make = value; }
    }

    public string CarModel
    {
      get { return this.model; }
      set { this.model = value; }
    }

    public int CarYear
    {
      get { return this.year; }
      set { this.year = value; }
    }

    public string CarOwner
    {
      get { return this.owner; }
      set
      {
        this.owner = value;
        // To avoid race condition
        var ownerchanged = this.OwnerChanged;
        if (ownerchanged != null)
          ownerchanged(value);
      }
    }

    public Car()
    {
    }
  }
}

Upvotes: 0

NVade
NVade

Reputation: 278

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.

Upvotes: 1

Luis Filipe
Luis Filipe

Reputation: 8708

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.

Upvotes: 2

Related Questions