Reputation: 7705
I have an interface with a bunch of methods with different signatures (context here is a WCF callback interface). My server has a list of clients. In response to events I want to call a method of the interface on every client. There is a bunch of boiler plate code around this call (check client is alive, should this client be include in list to callback, try catch, drop client if operation fails etc). Whats the best way to pull out this boiler plate code into a generic CallBackClients(SomeKindOfGenericDeligate method_to_call) where method_to_call is one of the interface methods.
ICallback {
void Fish(string my_string);
void SuperFish(int my_int, double my_double);
... etc ...
}
CallBackClients( -- ?? generic delegate ?? -- ) {
foreach (IClientCallback client in client_list) {
// The boiler plate code:
if (((ICommunicationObject)client.callback).State == CommunicationState.Opened) {
try {
Do method call based on delagate / lamda code passed in - how ??
}
catch (Exception e) {
Remove_client(client, method.ToString(), e);
}
}
else
Remove_client(client, method.ToString());
}
}
}
Pseudo code for caller:
void EventHandler_A() {
// Call Fish method on all clients:
CallBackClients(Fish("hello"));
}
void EventHandler_B() {
// Call SuperFish method on all clients:
CallBackClients(SuperFish(10, 5.3);
}
Upvotes: 1
Views: 160
Reputation: 46098
You can encapsulate a method to call later on any given IClientCallBack
in an Action<IClientCallBack>
:
CallBackClients(Action<IClientCallBack> actionOnDelegates) {
foreach (IClientCallback client in client_list) {
// The boiler plate code:
if (((ICommunicationObject)client.callback).State == CommunicationState.Opened) {
try {
actionOnDelegates(client);
}
catch (Exception e) {
Remove_client(client, method.ToString(), e);
}
}
else
Remove_client(client, method.ToString());
}
}
}
this would then be called like so; these create an anonymous method to call the method on the specified client
:
void EventHandler_A() {
// Call Fish method on all clients:
CallBackClients(client => client.Fish("hello"));
}
void EventHandler_B() {
// Call SuperFish method on all clients:
CallBackClients(client => client.SuperFish(10, 5.3);
}
Upvotes: 2