jim finegan
jim finegan

Reputation: 153

Task callback in one line C#

I have the following piece of code:

static void Main(string[] args)
{
    string param = "";
    doMessage doMss = new doMessage();
    doMss._msg.onResponseEvent += doMss_onResponseEvent;
    doMss.sendMsg(param);
}

private void doMss_onResponseEvent(object sender, responseEventArgs e)
{
    if (e.rxedMsg is mssCustomMessage)
    {
        if (e.rxeMsg.result.isSucessfull)
        {
            object returnResult = e.rxeMsg;
        }
    }
}        

Here the call back method returns success if all went well within and a result object. I need to do make multiple sequential calls to the above pattern however I wish to stop this interaction process if any one of the callbacks fails.

Upvotes: 0

Views: 245

Answers (1)

Jeroen van Langen
Jeroen van Langen

Reputation: 22073

This is not how you use events. Instead of using an event you should use a List<Func<doMessage, mssCustomMessage>>. Iterate the list and call the handler, stop until it return a valid message.

It is possible with events, but you have to call .GetInvocationList() on the event and call each delegate youself.

I'd rather not do that.

For example:

public class mssCustomMessage
{
    // ...............
}

public class doMessage
{

}

public class MyObject
{
    private List<Func<doMessage, mssCustomMessage>> _handlers = new List<Func<doMessage, mssCustomMessage>>();

    public void RegisterHandler(Func<doMessage, mssCustomMessage> handler)
    {
        _handlers.Add(handler);
    }

    public mssCustomMessage HandleMessage(doMessage msg)
    {
        // call all handlers until one replies with successful
        foreach(var handler in _handlers)
        {
            var response = handler(doMessage);
            if (response.result.isSucessfull)
                return response;
        }
    }
}

If you still want to stick to events, you should go for the add/remove keywords:

public class mssCustomMessage
{
    // ...............
}

public class doMessage
{

}

public class MyObject
{
    private List<Func<doMessage, mssCustomMessage>> _handlers = new List<Func<doMessage, mssCustomMessage>>();

    public mssCustomMessage HandleMessage(doMessage msg)
    {
        // call all handlers until one replies with successful
        foreach (var handler in _handlers)
        {
            var response = handler(doMessage);
            if (response.result.isSucessfull)
                return response;
        }

        return null;
    }

    public event Func<doMessage, mssCustomMessage> MyEvent
    {
        add
        {
            _handlers.Add(value);
        }
        remove
        {
            _handlers.Remove(value);
        }
    }
}

Upvotes: 2

Related Questions