Thread Basics-- using Timer to trigger Event at a specified internals
Timer provides a mechanism 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)
{
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 timercallback = new TimerCallback(hiron.GetResultAsync);
Timer timer = new Timer(timercallback, i, 0,2000);
//Blocks the current thread until the current waithhandle receives a signal
endProcessEvent.WaitOne();
}
we can see such windows: