一个实现自定义event的文章。。。我还没有完全摸透。。不知道有

80酷酷网    80kuku.com

  

The latest offering from Microsoft to support software development is the .NET Framework. Inside this vast Framework is the ASP.NET. The ASP.NET facilitates the application development community in generating high performance Web based applications that can be data rich and work in a heterogeneous environment.

In this discussion we will examine the steps to create a custom event that will alert the user or process that event has taken place under a specified condition. To understand how to setup the code structure to raise and handle events, an overview of the event architecture is needed.

Event Architecture

Below are a number of key points that encompass the .Net Framework event model.

- Events taking place in the .NET Framework are based upon the delegate model.
- The delegate class is the mechanism that allows the event sender to communicate with the event handler.
- An event sender can broadcast an event to a number of event handlers.
- An event handler must be registered with an event sender.


The fundamental definition of an event is: An event is a message that has been sent by an object due to some occurrence of an action within the workflow of the application. This action could be a button that has been clicked or specified timeout parameter value has been reached. This action triggers the event and the subsequent method that handles the event is initiated and the event is handled.

In the .NET framework, the sending object does not know what method will handle the event. Therefore, an agent must be utilized to handle the communication. This agent is the delegate class that holds a reference to the method that handles the event. The delegate class has an intrinsic signature and can only hold references to methods that obtain the same signature. You can equivocate the delegate class to a type-safe pointer to a callback. The event delegate has two parameters; these are the sending object and the returned data. Below in Listing 1 is generic declaration of the event delegate class.

Listing 1

Public delegate void EventHandler(object Sender, EventArgs e);

In order to initiate and handle custom events, event functionality needs to be provided. The fundamental structure is listed as follows:

- A class to hold the event data. This must be inherited from System.EventArgs.
- A delegate for the event.
- A class that raises the event.
- A class with a method that handles the event.


Now that we have discussed the fundamentals of event handling, we need a simple application to depict the event functionality.

Custom Events Application

The Custom Events Application is comprised of a simple Web Form that displays the event data message. This is shown in Figure 1.

Figure 1



In order to initiate some action that shows the functionality of event handling, a loop is created to count to some number and stop. During this count, a specific value is interrogated within the loop. When the specified value is equal to the loop value, the event is fired. In this case the value is 400000. The loop runs from 1 to 500000. When the value 400000 is reached the OnMessage method is called and the event is raised. Note: The InitEvent() method is called from Page_Load() method when the page is requested. The InitEvent() method is depicted in Listing 2.

Listing 2

private void InitEvent()
  {
    MessagingHandler mh = new MessagingHandler();
    MessageEvent me = new MessageEvent();
    me.Message += new MessageHandler(mh.GetMessageData);


    for (int i = 1; i <= 500000; i++)
    {
        if (i == 400000)
        {
          MessageEventArgs e = new MessageEventArgs();
          me.OnMessage(e);
          lblMessage.Text = mh.EventMessage;
        }
    }
  }


As you can see this is certainly overkill to display a line of text in a label field on a Web page. However, it is useful to examine the workflow of an event that is captured and handled in the .NET Framework. In order to make sense of the code fragment in Listing 2, we need to examine the classes that comprise the event structure. Below in Listing 3 shows the respective components that will raise and handle the event as it transpires.

Listing 3

public class MessageEventArgs : EventArgs
{
    public string MessageText
    {
        get
        {
            return ("There has been 400000 values processed.");
        }
    }
}


public delegate void MessageHandler(object sender, MessageEventArgs e);


public class MessageEvent
{
    public event MessageHandler Message;


    public void OnMessage(MessageEventArgs e)
    {
        if (Message != null)
        {
            Message(this, e);
        }
    }
}


public class MessagingHandler
{
    private string strMessage;
    public string EventMessage
    {
        get
        {
            return strMessage;
        }
        set
        {
            strMessage = value;
        }
    }


    public void GetMessageData(object sender, MessageEventArgs e)
    {
        string strMessage = e.MessageText;
        EventMessage = strMessage;
    }
}


The class MessageEventArgs will supply the data for event. Notice that it is inherited from EventArgs. As you can see MessageText is a property of the class and a get statement is utilized to return the data string. The delegate in this case is the MessageHandler. It has the sender object and the MessageEventArgs for the data in its argument list. Moving onto the class MessageEvent. This class will raise the event with the OnMessage() method by invoking the delegates. The MessagingHandler class will extract the event message from the MessageEventArgs and populate the EventMessage property so the message can be displayed on the Web page.

In summarization, we have a class that supplies the data, a delegate to provide the communication, a class to raise the event, and a class to handle the event. The basic workflow is as follows:

- The InitEvent() is initiated from the Page_Load() method when the page is requested.
- MessagingHandler mh = new MessagingHandler() instantiates the MessagingHandler class - Event Receiver.
- MessageEvent me = new MessageEvent() instantiates the MessageEvent class - Event Sender.
- me.Message += new MessageHandler(mh.GetMessageData) registers the event handler with the event source so that the MessagingHandler instance can receive alarm events. The += assignment operator adds the delegate to the list of delegates that are registered with the Message event.
- When the specified value is reached, MessageEventArgs e = new MessageEventArgs() is instantiated and the OnMessage() is called to raise the event.
- The OnMessage() method invokes the delegate which calls the GetMessageData() method to handle the event.
- The GetMessageData() method obtains the message text from the MessageEventArgs and populates the EventMessage property with the string data.
- The label field is populated with the EventMessage string property value and displayed on the Web page.


Run this example

[ run it ]

Conclusion

Since Web based applications are disconnected in nature and the handling of events are typically server-side the event message is displayed after the entire code sequence has transpired. This paradigm is not conducive for asynchronous processing due to the fire-and-forget processing. However, they can be useful if you are doing heavy server-side processing and validation before rendering the page.

The .NET Framework is providing the application developer a great deal of options to generate meaningful solutions to the enterprise, be it Web based applications, Windows Client based applications, or Server based Ser



分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: