Search code examples
c#eventsdelegatesevent-handlingdirectsound

How can I add events to a wrapped class in C#?


I am using the DirectSound framework and SecondaryBuffer objects. I am wrapping the SecondaryBuffer object in another class because I have some other values I want to associate with my SecondaryBuffer.

After playing a sound, I would like to dispose of the SecondaryBuffer, however, the only way to check to see if it is done playing is to check it's Status.

I would like to create an event that can be called when the Status of my SecondaryBuffer is the correct value.

Here is the snippet that contains my wrapped class.

public class WrappedBuffer
{
    public SecondaryBuffer Buffer { get; set; }
    //other variables here

    public WrappedBuffer(SecondaryBuffer buffer, ... and more)
    {
        this.Buffer = buffer;            
    }
}

Without events, I have to utilize a Timer and check the status like this;

if (!Buffer.Status.Playing)
{
     Buffer.Dispose();
}

Is there anyway that I can use events to call the Dispose() method of the SecondaryBuffer object without having to recheck the Status with a Timer.


Solution

  • There is no magic here; if the type doesn't already expose an event then you will have to poll until the state changes. That's how many events are implemented anyway. At some point you just have to watch for a change if the change is not occurring via one of your methods (in which case you would just fire the event when the value was set/changed).