您的位置:首页 > 其它

【读书笔记】事件Event

2010-03-23 17:52 288 查看
事件是一种允许类发送信号的方式,用来表明某个重要事情的发生。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Event
{
class Program
{
static void Main(string[] args)
{
LongTask It = new LongTask();
It.OnNotifyProgress += new LongTask.NotifyProgressDelegate(It_OnNotifyProgress);

It.PerformTask();

Console.ReadLine();
}

static void It_OnNotifyProgress(ProgressArgs pa)
{
Console.WriteLine("Progress on Long Task Complete. {0}% Complete.", pa.PercentComplete);

}
}

class LongTask
{
public delegate void NotifyProgressDelegate(ProgressArgs pa); // Declare a delegate

public event NotifyProgressDelegate OnNotifyProgress; // Create an event

public void PerformTask()
{
for (int i = 0; i < 10000; i++)
{
//Perform some processing
//...

//notify subscribers that progress was made
if (i % 100 == 0)
{
OnNotifyProgress(new ProgressArgs((int)i / 100));
}
}
}
}

class ProgressArgs
{
public int PercentComplete;

public ProgressArgs(int pctComplete)
{
PercentComplete = pctComplete;
}
}

}

事件概述

事件具有以下特点:

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

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

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

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

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

可以利用事件同步线程。

在 .NET Framework 类库中,事件是基于 EventHandler 委托和 EventArgs 基类的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: