Windows high-speed timer, multimedia timer Winmm.dll Library usage

Source: Internet
Author: User

The items used in the project are not allowed to be tested on the high-name timers. See the source code discovery is also used System.Timers.Timer or with the thread sleep way to achieve. 100 milliseconds is not allowed. Until a search, found that the use of multimedia timer Winmm.dll Millisecondtimer is available. The original is from the blog (dehai) Timer timing inaccurate questions and solutions. The code is as follows:

 Public sealed class Millisecondtimer:icomponent, IDisposable {//********************************************        Field ******************************************************************* private static timercaps caps;        private int interval;        private bool isrunning;        private int resolution;        Private TimerCallback TimerCallback;        private int Timerid; Property *****************************************************            <summary>/////</summary> public int Interval {            get {return this.interval; } set {if (Value < caps.periodmin) | |                (Value > Caps.periodmax)) {throw new Exception ("Beyond the timing range!                ");            } this.interval = value; }}///<summary&Gt </summary> public bool IsRunning {get {return T            his.isrunning;            }}///<summary>/////</summary> public ISite Site {            Set        Get }//***************************************************** Event ***************************************************  public event EventHandler disposed;        This event implements the Icomponet interface public event EventHandler Tick; ************************************************* of constructors and release functions        Static Millisecondtimer () {timegetdevcaps (ref caps, marshal.sizeof (caps));    } public Millisecondtimer () {this.interval = Caps.periodmin;  This.resolution = Caps.periodmin;            This.isrunning = false; This.timeRcallback = new TimerCallback (this.        Timereventcallback); Public Millisecondtimer (IContainer container): this () {container.        ADD (this);        } ~millisecondtimer () {timekillevent (This.timerid); }//***************************************************** Method ***************************************************            <summary>//////</summary> public void Start () { if (!isrunning) {Timerid = timeSetEvent (This.interval, This.resolution, This.timercall Back, 0, 1);                Run if (Timerid = = 0) {throw new Exception ("Unable to start timer") at intervals;            } isrunning = true;            }}///<summary>////</summary> public void Stop () { if (isrunning) {TimekilleveNT (This.timerid);            IsRunning = false;        }}///<summary>//Implement IDisposable interface///</summary> public void Dispose ()            {timekillevent (This.timerid); Gc.            SuppressFinalize (this); Disposed?.        Invoke (this, eventargs.empty); }//*************************************************** intrinsic function **************************************************** [DllImport ("Winmm.dll")] private static extern int timesetevent (int delay, int resolution, Ti        Mercallback callback, int user, int mode);        [DllImport ("Winmm.dll")] private static extern int timekillevent (int id);         [DllImport ("Winmm.dll")] private static extern int timegetdevcaps (ref timercaps caps, int sizeoftimercaps); private void timereventcallback (int id, int msg, int user, int param1, int param2) {Tick?.  Invoke (this, null); Raise Event}//********Internal Type **************************************************************** * * Private delegate void TimerCallback (int id, int msg, int user, int param1, int param2); timeSetEvent the signature of the callback function for the///<summary>///timer resolution (resolution).        Unit is MS, Ms? </summary> [StructLayout (layoutkind.sequential)] private struct Timercaps {publ            IC int periodmin;        public int Periodmax; }    }}
Test code
 Class Program {static dictionary<string, int> dtlist = new dictionary<string, int> ();            static void Main (string[] args) {//var timer = new Doublethreadtimer (100, 100); Timer.            Onrunningcallback + = Timer1_Tick; Timer.            Start ();            var timer1 = new Millisecondtimer (); Timer1.            Interval = 2; Timer1.            Tick + = Timer1_Tick; Timer1.            Start ();        Console.ReadLine ();            } private static void Timer1_Tick (object sender, EventArgs e) {var dt = DateTime.Now; String dtstr = dt.            ToString ("YyyyMMdd hhmmss");                if (Dtlist.containskey (DTSTR)) {dtlist[dtstr]++; If (dtlist[dtstr]% = = 0) {Console.WriteLine (dtstr + "--->"                    + dtlist[dtstr]);                Dtlist.remove (DTSTR);       }} else {         if (Dtlist.count > 1) {foreach (var item in dtlist) { Console.WriteLine (item. Key + "--->" + item.                     Value);                } dtlist.clear ();                            } dtlist.add (Dtstr, 1); }        }    }

  

Test conclusion: The time interval is set to 5 milliseconds, and the performance is stable. 2 milliseconds is sometimes accurate. Reliability is a lot faster than. NET timer.

Windows high-speed timer, multimedia timer Winmm.dll Library usage

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.