├── HighPrecisionTimer ├── TimerDemo │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── TimerDemo.csproj │ └── Program.cs ├── HighPrecisionTimer.sln └── HighPrecisionTimer │ ├── Properties │ └── AssemblyInfo.cs │ ├── HighPrecisionTimer.csproj │ └── MultimediaTimer.cs ├── LICENSE ├── README.md ├── .gitattributes └── .gitignore /HighPrecisionTimer/TimerDemo/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Mike Zboray 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HighPrecisionTimer 2 | A high precision timer in .NET 3 | 4 | There are often times where people would like regularly spaced events at a resolution greater than C# and Windows 5 | can normally provide (~15ms). This is a limitation of the standard timer mechanisms built into the Windows OS. 6 | There do exist high precision timing APIs for multimedia applications, but these are not exposed via .NET APIs. 7 | For applications that need timer event precision on the order of 1ms, these APIs are useful. This library is a quick 8 | example of using the [Multimedia Timer API](http://msdn.microsoft.com/en-us/library/windows/desktop/dd743609(v=vs.85).aspx). 9 | 10 | I will note that this API changes system wide settings that can degrade system performance (esp battery life), so buyer 11 | beware. Since Windows is not a real-time OS, the load on your system may cause the MM timer be delayed resulting 12 | in gaps of 100 ms that contain 100 events in quick succession, rather than 100 events spaced 1 ms apart. 13 | Some additional reading on [MM timers](https://blogs.msdn.microsoft.com/mediasdkstuff/2009/07/02/why-are-the-multimedia-timer-apis-timesetevent-not-as-accurate-as-i-would-expect/). 14 | 15 | I originally posted the code as an [answer](http://stackoverflow.com/a/24843946/517852) to a question on Stack Overflow -------------------------------------------------------------------------------- /HighPrecisionTimer/TimerDemo/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TimerDemo")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TimerDemo")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("70468ca5-872a-41d8-afb2-5eac1a9f59a9")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /HighPrecisionTimer/HighPrecisionTimer.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighPrecisionTimer", "HighPrecisionTimer\HighPrecisionTimer.csproj", "{F67353D6-1E54-4B18-9BF2-53DD27867983}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimerDemo", "TimerDemo\TimerDemo.csproj", "{70468CA5-872A-41D8-AFB2-5EAC1A9F59A9}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {F67353D6-1E54-4B18-9BF2-53DD27867983}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {F67353D6-1E54-4B18-9BF2-53DD27867983}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {F67353D6-1E54-4B18-9BF2-53DD27867983}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {F67353D6-1E54-4B18-9BF2-53DD27867983}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {70468CA5-872A-41D8-AFB2-5EAC1A9F59A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {70468CA5-872A-41D8-AFB2-5EAC1A9F59A9}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {70468CA5-872A-41D8-AFB2-5EAC1A9F59A9}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {70468CA5-872A-41D8-AFB2-5EAC1A9F59A9}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /HighPrecisionTimer/HighPrecisionTimer/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("HighPrecisionTimer")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("HighPrecisionTimer")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("f67353d6-1e54-4b18-9bf2-53dd27867983")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /HighPrecisionTimer/HighPrecisionTimer/HighPrecisionTimer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F67353D6-1E54-4B18-9BF2-53DD27867983} 8 | Library 9 | Properties 10 | HighPrecisionTimer 11 | HighPrecisionTimer 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 54 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /HighPrecisionTimer/TimerDemo/TimerDemo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {70468CA5-872A-41D8-AFB2-5EAC1A9F59A9} 8 | Exe 9 | Properties 10 | TimerDemo 11 | TimerDemo 12 | v4.6.1 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | {f67353d6-1e54-4b18-9bf2-53dd27867983} 55 | HighPrecisionTimer 56 | 57 | 58 | 59 | 66 | -------------------------------------------------------------------------------- /HighPrecisionTimer/TimerDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using HighPrecisionTimer; 9 | 10 | namespace TimerDemo 11 | { 12 | class Program 13 | { 14 | static void Main(string[] args) 15 | { 16 | var threadingResult = TestThreadingTimer(); 17 | var timerResult = TestMultimediaTimer(); 18 | var taskResult = TestTask(); 19 | 20 | Console.WriteLine($"Threading timer: {threadingResult.Summary()}"); 21 | Console.WriteLine($"Multimedia timer: {timerResult.Summary()}"); 22 | Console.WriteLine($"MultimediaTimer.Delay: {taskResult.Summary()}"); 23 | } 24 | 25 | private static TimingResult TestMultimediaTimer() 26 | { 27 | TimeSpan total = TimeSpan.Zero; 28 | int iterations = 0; 29 | Stopwatch s = new Stopwatch(); 30 | using (var timer = new MultimediaTimer() { Interval = 1 }) 31 | { 32 | timer.Elapsed += (o, e) => 33 | { 34 | var ts = s.Elapsed; 35 | lock (s) 36 | { 37 | total += ts; 38 | iterations++; 39 | } 40 | Console.WriteLine(ts.TotalMilliseconds); 41 | }; 42 | s.Start(); 43 | timer.Start(); 44 | Console.ReadKey(true); 45 | timer.Stop(); 46 | } 47 | 48 | lock (s) 49 | { 50 | return new TimingResult() 51 | { 52 | Elapsed = s.Elapsed, 53 | Iterations = iterations 54 | }; 55 | } 56 | } 57 | 58 | private static TimingResult TestThreadingTimer() 59 | { 60 | TimeSpan total = TimeSpan.Zero; 61 | int iterations = 0; 62 | Stopwatch s = new Stopwatch(); 63 | using (var timer = new Timer(o => 64 | { 65 | var ts = s.Elapsed; 66 | lock (s) 67 | { 68 | total += ts; 69 | iterations++; 70 | } 71 | Console.WriteLine(ts.TotalMilliseconds); 72 | 73 | }, null, 0, 1)) 74 | { 75 | s.Start(); 76 | Console.ReadKey(true); 77 | } 78 | 79 | lock (s) 80 | { 81 | return new TimingResult() 82 | { 83 | Elapsed = s.Elapsed, 84 | Iterations = iterations 85 | }; 86 | } 87 | } 88 | 89 | private static TimingResult TestTask() 90 | { 91 | try 92 | { 93 | using (var cancelled = new CancellationTokenSource()) 94 | { 95 | Console.CancelKeyPress += (o, e) => { cancelled.Cancel(); }; 96 | var result = TestTaskInner(cancelled.Token).GetAwaiter().GetResult(); 97 | return result; 98 | } 99 | } 100 | catch (OperationCanceledException) 101 | { 102 | return default(TimingResult); 103 | } 104 | } 105 | 106 | private static async Task TestTaskInner(CancellationToken token) 107 | { 108 | Stopwatch s = Stopwatch.StartNew(); 109 | TimeSpan prevValue = TimeSpan.Zero; 110 | int i = 0; 111 | while (true) 112 | { 113 | Console.WriteLine(s.Elapsed.TotalMilliseconds); 114 | await MultimediaTimer.Delay(1, token); 115 | if (Console.KeyAvailable) 116 | { 117 | break; 118 | } 119 | 120 | i++; 121 | } 122 | 123 | return new TimingResult() 124 | { 125 | Elapsed = s.Elapsed, 126 | Iterations = i 127 | }; 128 | } 129 | } 130 | 131 | struct TimingResult 132 | { 133 | public TimeSpan Elapsed; 134 | 135 | public int Iterations; 136 | 137 | public string Summary() 138 | { 139 | return $"{Elapsed.TotalMilliseconds / Iterations} ms / iteration"; 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | -------------------------------------------------------------------------------- /HighPrecisionTimer/HighPrecisionTimer/MultimediaTimer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace HighPrecisionTimer 11 | { 12 | /// 13 | /// A timer based on the multimedia timer API with 1ms precision. 14 | /// 15 | public class MultimediaTimer : IDisposable 16 | { 17 | private const int EventTypeSingle = 0; 18 | private const int EventTypePeriodic = 1; 19 | 20 | private static readonly Task TaskDone = Task.FromResult(null); 21 | 22 | private bool disposed = false; 23 | private int interval, resolution; 24 | private volatile uint timerId; 25 | 26 | // Hold the timer callback to prevent garbage collection. 27 | private readonly MultimediaTimerCallback Callback; 28 | 29 | public MultimediaTimer() 30 | { 31 | Callback = new MultimediaTimerCallback(TimerCallbackMethod); 32 | Resolution = 5; 33 | Interval = 10; 34 | } 35 | 36 | ~MultimediaTimer() 37 | { 38 | Dispose(false); 39 | } 40 | 41 | /// 42 | /// The period of the timer in milliseconds. 43 | /// 44 | public int Interval 45 | { 46 | get 47 | { 48 | return interval; 49 | } 50 | set 51 | { 52 | CheckDisposed(); 53 | 54 | if (value < 0) 55 | throw new ArgumentOutOfRangeException("value"); 56 | 57 | interval = value; 58 | if (Resolution > Interval) 59 | Resolution = value; 60 | } 61 | } 62 | 63 | /// 64 | /// The resolution of the timer in milliseconds. The minimum resolution is 0, meaning highest possible resolution. 65 | /// 66 | public int Resolution 67 | { 68 | get 69 | { 70 | return resolution; 71 | } 72 | set 73 | { 74 | CheckDisposed(); 75 | 76 | if (value < 0) 77 | throw new ArgumentOutOfRangeException("value"); 78 | 79 | resolution = value; 80 | } 81 | } 82 | 83 | /// 84 | /// Gets whether the timer has been started yet. 85 | /// 86 | public bool IsRunning 87 | { 88 | get { return timerId != 0; } 89 | } 90 | 91 | public static Task Delay(int millisecondsDelay, CancellationToken token = default(CancellationToken)) 92 | { 93 | if (millisecondsDelay < 0) 94 | { 95 | throw new ArgumentOutOfRangeException("millisecondsDelay", millisecondsDelay, "The value cannot be less than 0."); 96 | } 97 | 98 | if (millisecondsDelay == 0) 99 | { 100 | return TaskDone; 101 | } 102 | 103 | token.ThrowIfCancellationRequested(); 104 | 105 | // allocate an object to hold the callback in the async state. 106 | object[] state = new object[1]; 107 | var completionSource = new TaskCompletionSource(state); 108 | MultimediaTimerCallback callback = (uint id, uint msg, ref uint uCtx, uint rsv1, uint rsv2) => 109 | { 110 | // Note we don't need to kill the timer for one-off events. 111 | completionSource.TrySetResult(null); 112 | }; 113 | 114 | state[0] = callback; 115 | UInt32 userCtx = 0; 116 | var timerId = NativeMethods.TimeSetEvent((uint)millisecondsDelay, (uint)0, callback, ref userCtx, EventTypeSingle); 117 | if (timerId == 0) 118 | { 119 | int error = Marshal.GetLastWin32Error(); 120 | throw new Win32Exception(error); 121 | } 122 | 123 | return completionSource.Task; 124 | } 125 | 126 | public void Start() 127 | { 128 | CheckDisposed(); 129 | 130 | if (IsRunning) 131 | throw new InvalidOperationException("Timer is already running"); 132 | 133 | // Event type = 0, one off event 134 | // Event type = 1, periodic event 135 | UInt32 userCtx = 0; 136 | timerId = NativeMethods.TimeSetEvent((uint)Interval, (uint)Resolution, Callback, ref userCtx, EventTypePeriodic); 137 | if (timerId == 0) 138 | { 139 | int error = Marshal.GetLastWin32Error(); 140 | throw new Win32Exception(error); 141 | } 142 | } 143 | 144 | public void Stop() 145 | { 146 | CheckDisposed(); 147 | 148 | if (!IsRunning) 149 | throw new InvalidOperationException("Timer has not been started"); 150 | 151 | StopInternal(); 152 | } 153 | 154 | private void StopInternal() 155 | { 156 | NativeMethods.TimeKillEvent(timerId); 157 | timerId = 0; 158 | } 159 | 160 | public event EventHandler Elapsed; 161 | 162 | public void Dispose() 163 | { 164 | Dispose(true); 165 | } 166 | 167 | private void TimerCallbackMethod(uint id, uint msg, ref uint userCtx, uint rsv1, uint rsv2) 168 | { 169 | var handler = Elapsed; 170 | if (handler != null) 171 | { 172 | handler(this, EventArgs.Empty); 173 | } 174 | } 175 | 176 | private void CheckDisposed() 177 | { 178 | if (disposed) 179 | throw new ObjectDisposedException("MultimediaTimer"); 180 | } 181 | 182 | private void Dispose(bool disposing) 183 | { 184 | if (disposed) 185 | return; 186 | 187 | disposed = true; 188 | if (IsRunning) 189 | { 190 | StopInternal(); 191 | } 192 | 193 | if (disposing) 194 | { 195 | Elapsed = null; 196 | GC.SuppressFinalize(this); 197 | } 198 | } 199 | } 200 | 201 | internal delegate void MultimediaTimerCallback(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2); 202 | 203 | internal static class NativeMethods 204 | { 205 | [DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeSetEvent")] 206 | internal static extern UInt32 TimeSetEvent(UInt32 msDelay, UInt32 msResolution, MultimediaTimerCallback callback, ref UInt32 userCtx, UInt32 eventType); 207 | 208 | [DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeKillEvent")] 209 | internal static extern void TimeKillEvent(UInt32 uTimerId); 210 | } 211 | } 212 | --------------------------------------------------------------------------------