I run a console application and declared and instantiated an object of type Foo
. Besides the Main()
method I want to specify an additional method (lets call it ProcessMessages()
) and have it perform some work. The main job of Foo
is to accept messages that are sent to a tcp socket and processed. As part of the process I need to specify a function func<T>
to which such messages are passed. ProcessMessages()
(outside of Foo) is supposed to be such function. How can I register this function with foo without having to pass reference to its containing class?
Foo contains a TPL data flow bock which requires a func<T>
which operates on the queued items in the block. But the function is not contained within Foo but in the class that instantiated an object of type Foo. I am looking for the fastest way of later on calling this method even if I have to write more elaborate code. Ultimately I want to hide the underlying tpl data flow block within Foo and only want to call a function in Foo that sets up a tpl data flow block and registers with it a method that is located outside of Foo to which items can be passed later on. What is the best way to get this done? The registration part is the one which puzzles me.
EDIT: Here is some code that describes maybe better what I try to achieve:
a) In Main() I have the following method which is getting called from within a different class:
public void OnControlMessage(object sender, EventArgs args)
{
Console.WriteLine("Comp1 received Control Message");
}
I register this Method in the following way:
List<ZeroMqMessaging.CallBackMethod> registeredMethods = new List<ZeroMqMessaging.CallBackMethod>(){
new ZeroMqMessaging.CallBackMethod(MessageType.ControlMessage, OnControlMessage) };
b) The ActionBlock that invokes the callback looks as follows:
ActionBlock<Tuple<int, byte[]>> newActionBlock = new ActionBlock<Tuple<int, byte[]>>(x => callback.eventHandler(this, new MyEventArg(callback.messageType, x.Item2)));
OnControlMessage gets called correctly, however, I need to pass specific messages to OnControlMessage as part of EventArgs. I created a class MyEventArg that derives from EventArg but I still am not able to access members of MyEventArg in OnControlMessage.
Preferably I like to have OnControlMessage(ControlMessage message){...} in order to not to have to cast. How can I register this OnControlMessage so that I can call back this method with arguments of my choosing? I have potentially many different such callback methods so requirement is to stick to a 1-line short way to register as I currently do in a) when I create CallBackMethod objects. I hope this is somewhat clearer.
You probably need to create a delegate:
public delegate void MyMessageHandler(string message);
You can then use it like this:
public void Work(MyMessageHandler callback)
{
string message = "";
....
callback(message);
}
You then call it like this:
public Main()
{
Work(ProcessMessages);
}
public void ProcessMessages(string message)
{
....
}