-1

I am trying to get an event to trigger once the code resulting from the trigger of another event finished working. To me, this means that I have to trigger the second event just at the end of said code.

The first event, here, is directly taken from the Vimba Camera API I'm using, and it works perfectly fine. I read a few things on how to call an event properly (particularly the first anwer here), but I can't get my second event to run properly. I probably misunderstood something, but what ?

Here is a pseudo-code version of what I wrote :

public partial class Form1 : Form
{
    public delegate void SecondEventHandler(int[] myData);
    public event SecondEventHandler SomethingHappened;

    //Doing a lot of things irrelevant here

    myObj.OnFirstEvent += new Obj.OnFirstEventHandler(this.OnFirstEvent);

    private void OnFirstEvent(Data data)
    {
        //Doing things, and preparing myData
        SomethingHappened += new SecondEventHandler(HandleSomethingHappened);
    }

    void HandleSomethingHappened(int[] myData)
    {
        //Working with myData
    }
}
Trion
  • 115
  • 11
  • You should be providing a *working* example that demonstrates your problem, and you need to explain what specifically happens when you run the code and how that differs from what you want to happen. – Servy May 09 '18 at 13:15
  • You don't call the `HandleSomethingHappened` method, you just register it to the `SomethinHappend` event. Why don't you simply call `HandleSomethingHappend` at the end of `OnFirstEvent`? – René Vogt May 09 '18 at 13:15

2 Answers2

0

If you want to raise methods attached to second event:

    private void OnFirstEvent(Data data)
    {
        //Doing things, and preparing myData
        var h = SomethingHappened;
        if(h != null)
            h(pass your int[] parameter)
    }
Pablo notPicasso
  • 3,031
  • 3
  • 17
  • 22
0

Actually, the easiest yet the cleanest way to achive this is called continuation-passing-style. OnFirstEvent(Data data) should become OnFirstEvent(Data data, Action<int[]> continuator). Whenever it is not null, your code calls it.

However I do warn you: don't let it grow and spread all over your code. It's hard to debug and maintain from a long-term perspective. If you'd expect such an approach to be used extensively, then take a look in reactive extensions.

Zazaeil
  • 3,900
  • 2
  • 14
  • 31