事件

一.事件概述

事件具有以下特点:

  • 发行者确定何时引发事件,订户确定执行何种操作来响应该事件。

  • 一个事件可以有多个订户。一个订户可处理来自多个发行者的多个事件。

  • 没有订户的事件永远不会被调用。

  • 事件通常用于通知用户操作(如:图形用户界面中的按钮单击或菜单选择操作)。

  • 如果一个事件有多个订户,当引发该事件时,会同步调用多个事件处理程序。要异步调用事件,请参见使用异步方式调用同步方法

  • 可以利用事件同步线程。

  • 在 .NET Framework 类库中,事件是基于 EventHandler 委托和 EventArgs 基类的。

二. 使用.

     1.定义委托. (也可以基于系统的委托,这样就可以不用定义啦.)

     2.定义一个事件变量(基于定义的委托.)    //event 委托类型  变量名称.

     3.发布

     4.订阅

代码
namespace ConsoleApplication1
{
    
using System;
    
using System.Collections.Generic;

    
// Define a class to hold custom event info
    public class CustomEventArgs : EventArgs
    {
        
public CustomEventArgs(string s)
        {
            message 
= s;
        }
        
private string message;

        
public string Message
        {
            
get { return message; }
            
set { message = value; }
        }
    }

    
// Class that publishes an event
    class Publisher
    {

        
// Declare the event using EventHandler<T>
        public event EventHandler<CustomEventArgs> RaiseCustomEvent;   //2.定义一个事件变量.

        
public void DoSomething()
        {
            
// Write some code that does something useful here
            
// then raise the event. You can also raise an event
            
// before you execute a block of code.
            OnRaiseCustomEvent(new CustomEventArgs("Did something"));

        }

        
// Wrap event invocations inside a protected virtual method
        
// to allow derived classes to override the event invocation behavior
        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
        {
            
// Make a temporary copy of the event to avoid possibility of
            
// a race condition if the last subscriber unsubscribes
            
// immediately after the null check and before the event is raised.
            EventHandler<CustomEventArgs> handler = RaiseCustomEvent;

            
// Event will be null if there are no subscribers
            if (handler != null)
            {
                
// Format the string to send inside the CustomEventArgs parameter
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

                
// Use the () operator to raise the event.
                handler(this, e);                                          //3.发布
            }
        }
    }

    
//Class that subscribes to an event
    class Subscriber
    {
        
private string id;
        
public Subscriber(string ID)
        {
            id 
= ID;
            
// Subscribe to the event using C# 2.0 syntax
            
//pub.RaiseCustomEvent += HandleCustomEvent;
        }

        
// Define what actions to take when the event is raised.
        public void HandleCustomEvent(object sender, CustomEventArgs e)
        {
            Console.WriteLine(id 
+ " received this message: {0}", e.Message);
        }
    }

    
class Program
    {
        
static void Main(string[] args)
        {
            Publisher pub 
= new Publisher();
            Subscriber sub1 
= new Subscriber("sub1");
            Subscriber sub2 
= new Subscriber("sub2");

            pub.RaiseCustomEvent 
+= sub1.HandleCustomEvent;   //4.订阅
            pub.RaiseCustomEvent += sub2.HandleCustomEvent;

            
// Call the method that raises the event.
            pub.DoSomething();

            
// Keep the console window open
            Console.WriteLine("Press Enter to close this window.");
            Console.ReadLine();

        }
    }

}
原文地址:https://www.cnblogs.com/SouthAurora/p/1732076.html