Use code to learn C # & amp;. NET-delegate usage (event and timed processing)

Source: Internet
Author: User

Code compiling and running environment Visual Studio 2010. NET v4.0.30319

 
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading; // timed processing needs to be referenced
 
Namespace DelegateUseInEvent
{
/// <Summary>
/// If an event indicates a list of methods that an object will run under certain conditions, it is implemented using delegation;
/// Scheduled processing is a mechanism that uses the Timer function of Timer to process various tasks and methods at different time intervals. It also uses delegation.
/// </Summary>
Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("current managed Thread ID:" + Thread. CurrentThread. ManagedThreadId );
EventEx ();
TimerEx ();
Console. ReadKey (); // to ensure smooth timer execution, otherwise the main thread ends and the program ends, the timer does not run.
}
 
# Delegate in region event
/// <Summary>
/// A process of boiling water is simulated here. The water to be burned is defined as a kind of BoilingWater, which provides a temperature attribute.
/// As the temperature changes, if the boiling point reaches 100 degrees, the defined event (WaterBoiled) is triggered ).
/// In actual execution, two simulation methods are added for the event, one for simulation notification, and the other for simulating power-off for water-burning.
/// </Summary>
Static void EventEx ()
{
BoilingWater etc = new BoilingWater ();
Etc. WaterBoiled + = etc_BoiledTest; // simulation of boiling water for class instances
Etc. WaterBoiled + = etc_BoiledTest2; // a simulation method for adding power off to a class instance
For (int I = 98; I <102; I ++) // simulate the water burning process by assigning values to the object temperature,
{
Console. WriteLine ("temperature set for the object:" + I );
Etc. Temperature = I;
}
}
 
// Method 1 must be called for the event
Static void etc_BoiledTest (object o, EventArgs e)
{
BoilingWater SourceObject = (BoilingWater) o;
Console. WriteLine ("********** execution method 1 *********");
Console. WriteLine ("Notice: water is boiling! The water Temperature is: "+ SourceObject. Temperature );
Console. WriteLine ("managed Thread ID:" + Thread. CurrentThread. ManagedThreadId );
}
 
// Method 2 is called for all events
Static void etc_BoiledTest2 (object o, EventArgs e)
{
BoilingWater SourceObject = (BoilingWater) o;
Console. WriteLine ("********** method 2 *********");
Console. WriteLine ("Operation: power off! The water Temperature is: "+ SourceObject. Temperature );
}
 
// Define an object that is supported by the event
Class BoilingWater
{
Public delegate void EventTest (object o, EventArgs e );
Public event EventTest WaterBoiled; // defines an event,
Private int _ Temperature;
Public int Temperature // defines a Temperature attribute
{
Get
{
Return _ Temperature;
}
Set
{
_ Temperature = value;
If (value = 100) // if the water reaches 100 degrees, boiling triggers the event.
{
OnEventTest ();
}
}
}
 
// Event triggering Process
Private void OnEventTest ()
{
If (WaterBoiled! = Null) // determines whether it is null when an event is triggered.
{
WaterBoiled (this, new EventArgs ());
}
}
}
# Endregion
 
# Delegate in region scheduled Processing
/// <Summary>
/// The System. Threading of. NET provides a timer and a callback delegate type (TimerCallback) for scheduled processing.
/// </Summary>
Static void TimerEx ()
{
// TimerCallback is a delegate pointing to a non-return value method of an object type parameter for timer callback.
TimerCallback timerCallback = new TimerCallback (Method1); // Add the Method1 Method to the delegate.
TimerCallback + = o =>{ Console. WriteLine ("scheduled call method: Lambda expression method") ;}; // Add the lambda expression to the Delegate
TimerCallback + = delegate (object o) // Add the anonymous method to the delegate
{
Console. WriteLine ("scheduled call method: anonymous method ");
};
 
// Use the timer to call the method referenced in the delegate periodically
Timer timer = new Timer (timerCallback, // The parameter defines the list of methods or methods to be processed at a scheduled time (implemented by delegation)
Null, // This parameter defines the object type parameter passed to the method. null indicates that no parameter is passed.
0, // This parameter indicates the start time of the timer. 0 indicates the start time of understanding the timer.
1000); // This parameter indicates the interval of scheduled events, in milliseconds
}

// Define the method for timed Processing
Static void Method1 (object o)
{
Console. WriteLine ("scheduled call method: Method1; execution time:" + DateTime. Now. ToLongTimeString ());
Console. WriteLine ("managed Thread ID:" + Thread. CurrentThread. ManagedThreadId );
}
# Endregion
}

}

Running result and Description: The event is run in the main thread, and the scheduled processing method is the same as the task processing method, and the application thread in the thread pool is processed in the background; if the program does not press any key, it will continue to run and run the scheduled processing method every 1 second.

From: gxmark's column

Related Article

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.