【问题标题】:Executing function when subscribing to an event订阅事件时执行函数
【发布时间】:2014-03-18 11:26:47
【问题描述】:

当有人订阅我在课堂上制作的事件时,是否可以执行一些代码。一个简短的解释:当有人订阅此事件时,我需要配置一台外部电脑向我发送数据,因此当收到该数据时,我可以抛出该事件。

public class test
        {
            public event EventHandler myEvent;

            private void Method1()
            { 
                //this needs to be executed when someone subscribes to the event
            }

            private void Method2()
            {
                //this needs to be executed when someone unsubscribes to the event
            }
        }

【问题讨论】:

    标签: c# events


    【解决方案1】:

    您可以创建自己的 add / remove 方法

     private EventHandler myEvent;
        public event EventHandler MyEvent {
            add {
                myEvent += value;
                if(myEvent != null) ExecuteCode();
            }
            remove {
                myEvent -= value;
            }
        }
    

    小心你的函数是否应该是线程安全的,在这种情况下你需要一个锁来确保它被同步。

    【讨论】:

    • 非常感谢您,先生!这让我很开心:D
    • 我很高兴它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多