In some scenarios that require remote triggering, such as the setinterval function in Javascript, what do you use in. Net?
Is it system. Timer. timer?
Or
While (true)
{
Thread. Sleep (1000 );
}
Today, we will compare timer and sleep.
Result:
Thread. Sleep: ask who is competing for the peak.
Space:
Type |
Work set |
Virtual bytes |
Page file bytes |
Thread Count |
Handle |
Timer |
8.990.720 |
114.978.816 |
11.444.small |
4 |
115 |
Thread. Sleep |
6.590464 |
104.296.448 |
7.143.424 |
3 |
95 |
Thread. Sleep wins
Time:
Type |
Start Time |
Interval |
Times |
Finish time |
Timer |
11: 53: 37: 416 |
10 ms |
100000 |
12: 19: 37: 555 |
Thread. Sleep |
11: 53: 37: 432 |
10 ms |
100000 |
12: 19: 36: 713 |
Timer and thread. Sleep are flat, but thread. Sleep is better.
Analysis:
Thread. Sleep calls the kernel command directly, and the thread is suspended. The CPU executes the re-sorting of the queue.
Each time elapsed is run by timer, a new thread is retrieved from the thread pool, and there is a loss of the thread pool for multiple accesses.
Test code:
Code
Class Program
{
Private Static system. Timers. Timer _ timer;
Private Static volatile int _ max = 100000;
Private Static volatile int _ threadmax = 100000;
Static void main (string [] ARGs)
{
Console. writeline (system. datetime. Now. tostring () + system. datetime. Now. millisecond. tostring ());
Starttimer ();
Console. writeline (system. datetime. Now. tostring () + system. datetime. Now. millisecond. tostring ());
Startthread ();
Console. Readline ();
}
Static private void startthread ()
{
Thread S = new thread (threadgo );
S. Start ();
}
Static private void threadgo ()
{
While (true)
{
Thread. Sleep (10 );
_ Threadmax --;
If (_ threadmax <0) break;
}
Console. writeline ("threadgo" + system. datetime. Now. tostring () + system. datetime. Now. millisecond. tostring ());
Thread. currentthread. Abort ();
}
Static private void starttimer ()
{
_ Timer = new system. Timers. Timer ();
_ Timer. autoreset = true;
_ Timer. interval = 10;
_ Timer. elapsed + = new elapsedeventhandler (_ timer_elapsed );
_ Timer. Start ();
}
Static void _ timer_elapsed (Object sender, elapsedeventargs E)
{
_ Max --;
If (_ max <0)
{
Console. writeline ("_ timer_elapsed" + system. datetime. Now. tostring () + system. datetime. Now. millisecond. tostring ());
_ Timer. Stop ();
_ Timer. Dispose ();
}
}
}