Thread basics-using timer to trigger event at a specified Internals

Source: Internet
Author: User
1. What's timer
Timer provides a mechanic for executing a method in at specified intervals.
The hierarchy can be the following:
System. Threading. timer;
System. Timer. timer;
System. Windows. Form. timer;

2. Relevant Method about timer.

Public class asyntest
{
Private int result ;//Which is get randonly asynchrounousely by method getresultasync;
Manualresetevent endprocessevent;

Public asyntest (manualresetevent endprocessevent)
{< br> This. endprocessevent = endprocessevent;
}

Int getresult ()
{
Random RD = new random ();
Result = (INT) (100 * RD. Next () % 100;
Console. writeline ("Get value asynchronousely! ");
Return result;
}

Public Delegate int getresultdelegate ();

Public void getresultasync (Object OBJ)
{
Getresultdelegate GRD = new getresultdelegate (getresult );
Asynccallback cb = new asynccallback (This. getintergerfromcallback);
Iasyncresult AR = GRD. begininvoke (CB, null );
Console. writeline ("result = {0}", result );
If (result % 2 = 0)
Console. writeline ("result is an even number ");
}

// Get the result asynchronousely
Public void getintergerfromcallback (iasyncresult AR)
{
Try
{
Getresultdelegate del = (getresultdelegate) (asyncresult) Ar). asyncdelegate;
Del. endinvoke (AR );
}
Catch (exception ex)
{
Console. writeline (ex. Message );
}

}

Static void main (string [] ARGs)
{
System. Threading. thread. currentthread. Name = "mainthread ";
Manualresetevent endprocessevent = new manualresetevent (false );
Asyntest hiron = new asyntest (endprocessevent );
Timercallback = new timercallback (hiron. getresultasync );
Timer timer = new timer (timercallback, I, 0, 2000 );
// Blocks the current thread until the current waithhandle es a signal
Endprocessevent. waitone ();

}
We can see such windows:

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.