Use of events in C #

Source: Internet
Author: User

An example is used to illustrate the use of events.

Create a simple class named Filewatch that contains the event Onfilechange. The class checks the directory in which the application is executing (the current

directory, usually the project name/bin/debug), if there is a file test.txt. If the file is deleted or created, the event is triggered.

A method Monitorfile is also provided to continuously query the file.

Method:

Before creating an available event, first declare a delegate that is placed outside the class. public delegate void Filewatcheventhandler (Object Sender,eventargs e);

Next, create the class Filewatch. Then declare the event, noting that the type of event is the delegate we defined earlier.

public event Filewatcheventhandler Filewatchevent;

Now create the Method Onfilechange (), which will trigger the event when the method is called:

protected virtual void Onfilechange (EventArgs e) {if (filewatchevent!=null) {filewatchevent (this,e); } }

Finally, create the method Monitorfile (),

public void Monitorfile () {bool bcurrentstatus;          while (true) {bcurrentstatus = file.exists ("test.txt");          if (bcurrentstatus! = _blaststatus)//_blaststatus is a private field with an initial value of false;              {_blaststatus = Bcurrentstatus;          Onfilechange (Eventargs.empty); }

Thread.Sleep (250); } }

The complete code is as follows:

Using System;  Using System.Threading; Using System.IO;

Namespace Sample.event {

public delegate void Filewatcheventhandler (object sender, EventArgs e);

public class Filewatch {private bool _blaststatus = false;             Public Filewatch () {/////TODO: Add constructor logic here// }

            public Event Filewatcheventhandler filewatchevent; 

            protected virtual void Onfilechange ( EventArgs e)             {                   if (filewatchevent! = null)                    {                                                   Filewatchevent (this, e);                  }             } 

public void Monitorfile () {bool bcurrentstatus;

while (true) {bcurrentstatus = file.exists ("test.txt");

                        //status does not match, the description file is deleted or recreated, the event is triggered at this time;                          if (bcurrentstatus! = _ Blaststatus)                          {                               _ Blaststatus = Bcurrentstatus;                                Onfilechange (Eventargs.empty);                        } 

Thread.Sleep (250); }

}       } }

Use: Create a Windows application to test the events in the Filewatch we established earlier. First compile the project you just created

, generate Assembly:FileWatch.dll, and then add references. Of course, adding project references directly is also possible. Then in the Windows app

Namespaces are added to the sequence:

Using Sample.event;

Then in the application class, define a private field, type the class we created earlier Filewatch:public class FrmMain:System.Windows.Forms.Form {private Samp Le. Event.filewatch Filewatcheventsource;

and instantiate the object in the constructor;

Public Frmmain () {InitializeComponent ();

Filewatcheventsource = new Sample.Event.FileWatch ();

The local method Onfilechange is then connected to the event:

Filewatcheventsource.filewatchevent+=new Sample.Event.FileWatchEventHandler (Onfilechange);

We need to invoke the Monitorfile method to trigger the event. In this example, we use threads to control the Monitorfile method. This can be done in

Run this method to trigger an event when the application is idle.

THRD = new Thread (new ThreadStart (Filewatcheventsource.monitorfile)); Thrd. Start ();

Finally, we need to know if the event is triggered, in order to record the event triggered history, we add the trigger in the ListBox control

Capacity. Because the method called after the event is triggered is onfilechange, we put the action in the method:

private void Onfilechange (object Sender, EventArgs e) {listBox.Items.Add (DateTime.Now.ToString () + ": File changed.");

When an event is triggered, Eventhanler passes a reference to the sender and the EventArgs class. The EventArgs class is usually in the event source and triggers the thing

Transfer information between the components. In this case, no information is passed and the EventArgs class is not used. Instead, it just adds the event to the listbox

In

The results of the operation are as follows:

Conclusion: The essentials of using events in C #:

First, to establish a delegate in the form: public delegate void delegate name (object sender, EventArgs e); Note: The delegate is a function pointer in C, and the parameter table is fixed in the event because of the information about the object to pass the event and trigger the event. The general format of the delegate name is: Name +envenhandle. This name is more canonical.

Then, create an event field: The public event delegate type events name; Note: The event keyword represents the events, and the return type is the delegate;

Define a method, handle the event, and in this case Onfilechange (EventArgs e). The event should be called in the method: the event name (object, EventArgs), where object is generally itself, and the argument should be the actual argument that This,eventargs should pass in Onfilechange, especially the value to pass the event.

Finally, you will create a method that triggers the event. In the example, Monitorfile (), in its method, invokes Onfilechange to achieve the purpose of triggering the event when the condition is satisfied.

When you reuse an event, you typically define two methods, one that is consistent with the delegate signature of the event definition, in this case Onfilechange (Object Sender,eventargs e);

Note In the example, the Onfilechange of the form class and the Onfilechange of the event class are different. The latter is used to invoke events, while the former is used to bind events. The method of binding an event is simple, with + = representing the Add event, or-= for the Delete event. Example of Filewatcheventsource.filewatchevent+=new Sample.Event.FileWatchEventHandler (Onfilechange); That is to add an event.

Example: Start the thread first (THD. Start ()), and then call the Monitorfile () method. Cause the event to occur, after the filewatchevent is generated, because we bind the event filewatchevent to the Onfilechange () method. Thus, the Onfilechange () method of the local-window class is called to enable the addition of information in the listbox.

Original: http://wayfarer.cnblogs.com/archive/2004/04/20/6712.html

Use of events in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.