Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
Hello,
I have two classes ClassSender generates an event and ClassReceiver suppose to handle the event.
From what i have seen in the internet the Receiver class must have a reference to Sender class in order to register his handler of the event.
Is there a way to register on the event without having a reference of the Sender class?
 
Thanks
Posted 16-Feb-13 4:19am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

It is possible with dynamic subscription. You will need a mapper class that will help you achieve this. lets say you have a Publisher class that broadcast financial data periodically - Its keeps on running and whenever it has some new information it just publishes it:
 
for the broadcasting it has a delegate defined like following:
 
public delegate void BroadcastData(string ticker, string command, decimal value);
 
Now there could be many subscribers interested in these broadcasts - but they may or may not be interested in the exact piece of information that is being published.
 
Lets assume that Subscriber S1 is interested in Ticker A, B and C and Command PriceClose where as S2 is interested in Ticker X, Y and Z and Command PriceClose & PriceOpen.
 
To solve this problem you need to put a mapper class - could be a singleton object.
 
See the example code - Here Subscriber gets the update from Publisher but not directly. Its the mapper who manages things between.
 
        public delegate void BroadcastData(string ticker, string command, decimal value);
        public delegate void MarketUpdate(List<FinancialData> fData);
 
        public class BroadcastingService {
 
            public static readonly BroadcastingService Instance = new BroadcastingService();
 
            public event BroadcastData OnDataUpdate;
 
            // This is a dummy implementation. in real world it will know what it has to publish when.
            private void Publish()
            {
                if (OnDataUpdate != null)
                    OnDataUpdate("SomeTicker", "SomeCommand", 1000.00m);
            }
        }
 
        public class Subscriber
        {
            public Subscriber() {
                Mapper.Register("IBM,VOD".Split(',').ToList(), "Priceclose,priceopen".Split(',').ToList(), HandleUpdate);
            }
 
            private void HandleUpdate(List<FinancialData> financialUpdate) { 
                // DO clientside coding
            }
        }
 
        public class FinancialData {
            public string ticker;
            public string command;
            public decimal value;
        }
 
        public static class Mapper {
 
            static Dictionary<MarketUpdate, KeyValuePair<List<string>, List<string>>> Listners = 
                new Dictionary<MarketUpdate, KeyValuePair<List<string>, List<string>>>();
 
            static List<FinancialData> allUpdate = new List<FinancialData>();
            static System.Threading.Timer timer = null;
 
            static Mapper() {
                BroadcastingService.Instance.OnDataUpdate += new BroadcastData(Instance_OnDataUpdate);
                timer = new System.Threading.Timer(st => {
                    NotifySubscribers();
                });
                timer.Change(1000, 1000); // Update every second
            }
 
            static void Instance_OnDataUpdate(string ticker, string command, decimal value)
            {
                var fData = allUpdate.Find(fd => fd.ticker == ticker && fd.command == command);
                if (fData == null)
                {
                    fData = new FinancialData() { ticker = ticker, command = command, value = value };
                    allUpdate.Add(fData);
                }
                else {
                    fData.value = value;
                }
            }
            
            public static void Register(List<string> tickers, List<string> commands, MarketUpdate callback)
            {
                Listners.Add(callback, new KeyValuePair<List<string>,List<string>>(tickers, commands));
            }
            public static void UnRegister(MarketUpdate callback) {
                Listners.Remove(callback);
            }
 
            public static void NotifySubscribers(){
                foreach (var lt in Listners)
                {
                    List<FinancialData> financialUpdate = new List<FinancialData>();
                    foreach (string tkr in lt.Value.Key)
                    {
                        foreach (string cmd in lt.Value.Value)
                        {
                            var fData = allUpdate.Find(fd => fd.ticker == tkr && fd.command == cmd);
                            if (fData != null) {
                                financialUpdate.Add(fData);
                            }
                        }
                    }
                    lt.Key.BeginInvoke(financialUpdate, null, null);
                }
            }
        }
 
 
We can have such loose links; But to get update of course in the chain somewhere the reference of publisher has to be maintained. Its just that - it's a global Instance here who does this instead of subscriber doing so by itself.
  Permalink  
v5
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Not really - unless your event is static, which is very, very rare.
 
It's not normally a problem: normally the event is attached when you create the instance, and can be forgotten about from then on.
ClassSender mySender = new ClassSender();
mySender.SenderEvent += new EventHandler(MyEventHandlerMethod);
If you haven't got an instance, then it's difficult to signal an event anyway because (unless all the code is static) no other code knows the instance exists!
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 495
1 Maciej Los 340
2 Richard MacCutchan 265
3 BillWoodruff 225
4 Mathew Soji 200
0 OriginalGriff 8,804
1 Sergey Alexandrovich Kryukov 7,457
2 DamithSL 5,689
3 Maciej Los 5,279
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web03 | 2.8.1411028.1 | Last Updated 18 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100