├── .gitignore ├── LICENSE ├── NProg.Demo ├── App.config ├── NProg.Demo.csproj ├── Program.cs └── Properties │ └── AssemblyInfo.cs ├── NProg.Test ├── NProg.Test.csproj ├── Properties │ └── AssemblyInfo.cs ├── Tests.cs └── packages.config ├── NProg.sln ├── NProg ├── NProg.csproj └── Tracker.cs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Todd Menier 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 | -------------------------------------------------------------------------------- /NProg.Demo/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /NProg.Demo/NProg.Demo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {31377CB5-12A1-494B-BA4E-55D16AC724EC} 8 | Exe 9 | NProg.Demo 10 | NProg.Demo 11 | v4.7 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | {c07a77a6-6afe-4492-9b06-ea278ed5f500} 54 | NProg 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /NProg.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using NProg; 8 | 9 | namespace NProg.Demo 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) { 14 | var workItems = Enumerable.Range(1, 2001).ToList(); 15 | 16 | var tracker = new Tracker(workItems.Count); 17 | tracker.Every(100.ItemsDone(), LogCount); 18 | tracker.Every(25.PercentDone(), LogPercent); 19 | tracker.Every(10.Seconds(), LogSeconds); 20 | tracker.On(50.PercentDone(), prog => Console.WriteLine("hey we're half done!")); 21 | tracker.OnComplete(LogDone); 22 | 23 | tracker.Start(); 24 | foreach (var item in workItems) { 25 | tracker.ItemStarted(); 26 | try { 27 | ProcessItem(item); 28 | tracker.ItemSucceeded(); 29 | } 30 | catch (Exception) { 31 | tracker.ItemFailed(); 32 | } 33 | } 34 | Console.ReadLine(); 35 | } 36 | 37 | private static void ProcessItem(int item) { 38 | Thread.Sleep(10); 39 | if (item == 999) 40 | throw new Exception("this one failed!"); 41 | } 42 | 43 | private static void LogCount(Progress prog) { 44 | Console.WriteLine($"\t{prog.ItemsDone} of {prog.TotalItems} done ({prog.PercentDone}%)"); 45 | } 46 | 47 | private static void LogPercent(Progress prog) { 48 | Console.WriteLine($"{prog.PercentDone}% done. estimated competion time: {prog.EstEndTimeLocal:h:mm:ss tt}"); 49 | } 50 | 51 | private static void LogSeconds(Progress prog) { 52 | Console.WriteLine($"{prog.ElapsedSeconds} seconds elapsed, {prog.ItemsDone} of {prog.TotalItems} done"); 53 | } 54 | 55 | private static void LogDone(Progress prog) { 56 | Console.WriteLine($"Done! Completed in {prog.ElapsedSeconds} seconds, {prog.ItemsSucceeded} succeeded, {prog.ItemsFailed} failed."); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /NProg.Demo/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("NProg.Demo")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("NProg.Demo")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 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("31377cb5-12a1-494b-ba4e-55d16ac724ec")] 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 | -------------------------------------------------------------------------------- /NProg.Test/NProg.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FF51DD82-5DF9-482F-8519-96B07F436537} 8 | Library 9 | Properties 10 | NProg.Test 11 | NProg.Test 12 | v4.7 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 | ..\packages\NUnit.3.9.0\lib\net45\nunit.framework.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | {c07a77a6-6afe-4492-9b06-ea278ed5f500} 55 | NProg 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /NProg.Test/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("NProg.Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("NProg.Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 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("ff51dd82-5df9-482f-8519-96b07f436537")] 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 | -------------------------------------------------------------------------------- /NProg.Test/Tests.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 NUnit.Framework; 9 | using NProg; 10 | 11 | namespace NProg.Test 12 | { 13 | [TestFixture] 14 | public class Tests 15 | { 16 | [Test] 17 | public void item_tracking_works() { 18 | var logCount = 0; 19 | var itemsStarted = 0; 20 | var percentDone = 0; 21 | 22 | var tracker = new Tracker(5001); 23 | 24 | // should be called 25 times 25 | tracker.Every(200.ItemsStarted(), prog => { 26 | itemsStarted += 200; 27 | Assert.AreEqual(itemsStarted, prog.ItemsStarted); 28 | Assert.AreEqual(1, prog.ItemsInProgress); 29 | Assert.AreEqual(itemsStarted - 1, prog.ItemsDone); 30 | Assert.AreEqual(itemsStarted - 1, prog.ItemsSucceeded); 31 | Assert.AreEqual(0, prog.ItemsFailed); 32 | Assert.AreEqual(5001 - itemsStarted, prog.ItemsRemaining); 33 | logCount++; 34 | }); 35 | 36 | // should be called 4 times 37 | tracker.Every(25.PercentDone(), prog => { 38 | percentDone += 25; 39 | Assert.AreEqual(percentDone, prog.PercentDone); 40 | Assert.AreEqual(5000 * percentDone / 100 + 1, prog.ItemsDone); 41 | logCount++; 42 | }); 43 | 44 | // should be called 1 time 45 | tracker.On(50.PercentDone(), _ => logCount++); 46 | 47 | // should be called 1 time 48 | tracker.OnComplete(prog => { 49 | Assert.AreEqual(5001, prog.ItemsDone); 50 | logCount++; 51 | }); 52 | 53 | for (var i = 0; i < 5001; i++) { 54 | tracker.ItemStarted(); 55 | // process item 56 | tracker.ItemSucceeded(); 57 | } 58 | 59 | Assert.AreEqual(31, logCount); 60 | } 61 | 62 | [Test] 63 | public void time_tracking_works() { 64 | var count = 0; 65 | 66 | var tracker = new Tracker(9); 67 | tracker.Every(TimeSpan.FromMilliseconds(100), prog => count++); 68 | 69 | Thread.Sleep(200); // timer shouldn't fire yet 70 | 71 | tracker.Start(); 72 | for (var i = 0; i < 10; i++) { 73 | Thread.Sleep(100); 74 | } 75 | tracker.Stop(); 76 | 77 | Thread.Sleep(200); // timer should have stopped firing 78 | 79 | Assert.AreEqual(9, count); 80 | // 1000 ms and change should have elapsed, just check fo 9xx 81 | Assert.GreaterOrEqual(9, tracker.GetProgress().ElapsedTime.Milliseconds / 100); 82 | } 83 | 84 | [Test] 85 | public void tracker_is_thread_safe() { 86 | var counts = new List(); 87 | 88 | var tracker = new Tracker(10); 89 | tracker.Every(1.ItemsDone(), prog => counts.Add(prog.ItemsDone)); 90 | 91 | Task.WaitAll( 92 | Task.Run(() => tracker.ItemSucceeded()), 93 | Task.Run(() => tracker.ItemSucceeded()), 94 | Task.Run(() => tracker.ItemSucceeded()), 95 | Task.Run(() => tracker.ItemSucceeded()), 96 | Task.Run(() => tracker.ItemSucceeded()), 97 | Task.Run(() => tracker.ItemSucceeded()), 98 | Task.Run(() => tracker.ItemSucceeded()), 99 | Task.Run(() => tracker.ItemSucceeded())); 100 | 101 | Assert.AreEqual(8, counts.Count); 102 | CollectionAssert.Contains(counts, 1); 103 | CollectionAssert.Contains(counts, 2); 104 | CollectionAssert.Contains(counts, 3); 105 | CollectionAssert.Contains(counts, 4); 106 | CollectionAssert.Contains(counts, 5); 107 | CollectionAssert.Contains(counts, 6); 108 | CollectionAssert.Contains(counts, 7); 109 | CollectionAssert.Contains(counts, 8); 110 | } 111 | 112 | [Test] 113 | public void now_runs_immediately() { 114 | var tracker = new Tracker(10); 115 | var nowRan = false; 116 | tracker.Now(prog => nowRan = true); 117 | Assert.IsTrue(nowRan); 118 | } 119 | 120 | [Test] 121 | public async Task async_tracking_works() { 122 | var tracker = new Tracker(10); 123 | var counter = 0; 124 | 125 | tracker.Every(2.ItemsDone(), async prog => { 126 | await Task.Delay(1000); 127 | counter++; 128 | }); 129 | 130 | for (var i = 0; i < 10; i++) 131 | tracker.ItemSucceeded(); 132 | 133 | // counter should get incremeted 5 times, but not until we await completion 134 | Assert.AreEqual(0, counter); 135 | await tracker.CompleteAsync(); 136 | Assert.AreEqual(5, counter); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /NProg.Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /NProg.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2005 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NProg.Test", "NProg.Test\NProg.Test.csproj", "{FF51DD82-5DF9-482F-8519-96B07F436537}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{68E9283A-462C-4B98-B7C5-323967A04CE1}" 9 | ProjectSection(SolutionItems) = preProject 10 | README.md = README.md 11 | EndProjectSection 12 | EndProject 13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NProg.Demo", "NProg.Demo\NProg.Demo.csproj", "{31377CB5-12A1-494B-BA4E-55D16AC724EC}" 14 | EndProject 15 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NProg", "NProg\NProg.csproj", "{C07A77A6-6AFE-4492-9B06-EA278ED5F500}" 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {FF51DD82-5DF9-482F-8519-96B07F436537}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {FF51DD82-5DF9-482F-8519-96B07F436537}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {FF51DD82-5DF9-482F-8519-96B07F436537}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {FF51DD82-5DF9-482F-8519-96B07F436537}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {31377CB5-12A1-494B-BA4E-55D16AC724EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {31377CB5-12A1-494B-BA4E-55D16AC724EC}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {31377CB5-12A1-494B-BA4E-55D16AC724EC}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {31377CB5-12A1-494B-BA4E-55D16AC724EC}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {C07A77A6-6AFE-4492-9B06-EA278ED5F500}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {C07A77A6-6AFE-4492-9B06-EA278ED5F500}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {C07A77A6-6AFE-4492-9B06-EA278ED5F500}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {C07A77A6-6AFE-4492-9B06-EA278ED5F500}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {9A5D608D-1BC0-4551-8303-540F45BF5B6C} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /NProg/NProg.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /NProg/Tracker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace NProg 8 | { 9 | public class Tracker 10 | { 11 | private long _startTime = DateTime.UtcNow.Ticks; 12 | private long _endTime; 13 | private int _total; 14 | private int _started; 15 | private int _succeeded; 16 | private int _failed; 17 | 18 | private List _actions = new List(); 19 | private List _tasks = new List(); 20 | private List _timers = new List(); 21 | 22 | public Tracker(int itemCount) => _total = itemCount; 23 | 24 | public void Start() { 25 | _startTime = DateTime.UtcNow.Ticks; 26 | _timers.ForEach(t => t.Start(this)); 27 | } 28 | 29 | public void Stop() { 30 | _endTime = DateTime.UtcNow.Ticks; 31 | _timers.ForEach(t => t.Stop()); 32 | } 33 | 34 | public void Every(Trigger trigger, Action action) => _actions.Add(new ProgressAction { Trigger = trigger, Action = action, Recurring = true }); 35 | public void On(Trigger trigger, Action action) => _actions.Add(new ProgressAction { Trigger = trigger, Action = action, Recurring = false }); 36 | public void Every(TimeSpan interval, Action action) => _timers.Add(new TimerAction { Interval = interval, Action = action }); 37 | public void OnComplete(Action action) => On(_total.ItemsDone(), action); 38 | public void Now(Action action) => action(GetProgress()); 39 | 40 | public void Every(Trigger trigger, Func action) => _actions.Add(new ProgressAction { Trigger = trigger, AsyncAction = action, Recurring = true }); 41 | public void On(Trigger trigger, Func action) => _actions.Add(new ProgressAction { Trigger = trigger, AsyncAction = action, Recurring = false }); 42 | public void Every(TimeSpan interval, Func action) => _timers.Add(new TimerAction { Interval = interval, AsyncAction = action } ); 43 | public void OnComplete(Func action) => On(_total.ItemsDone(), action); 44 | public void Now(Func action) => action(GetProgress()); 45 | 46 | private readonly object _lock = new object(); 47 | 48 | public void ItemStarted() => ProcessTriggers(ref _started); 49 | public void ItemSucceeded() => ProcessTriggers(ref _succeeded); 50 | public void ItemFailed() => ProcessTriggers(ref _failed); 51 | 52 | /// 53 | /// Returns a completion task that should be awaited if any async actions were triggered. 54 | /// Async actions are NOT awaited inline. 55 | /// 56 | public Task CompleteAsync() => Task.WhenAll(_tasks); 57 | 58 | public Progress GetProgress() => new Progress(_startTime, _endTime, _total, _started, _succeeded, _failed); 59 | 60 | private void ProcessTriggers(ref int fieldToIncrement) { 61 | var fired = new List(); 62 | Progress prog; 63 | 64 | lock (_lock) { 65 | fieldToIncrement++; 66 | prog = GetProgress(); 67 | fired = _actions.Where(act => act.Trigger.IsFired(prog)).ToList(); 68 | 69 | foreach (var act in fired) { 70 | if (!act.Recurring) 71 | _actions.Remove(act); 72 | } 73 | 74 | _tasks.RemoveAll(t => t.IsCompleted); 75 | } 76 | 77 | fired.ForEach(act => act.Invoke(prog, _tasks)); 78 | } 79 | 80 | private abstract class ActionBase 81 | { 82 | public Action Action { get; set; } 83 | public Func AsyncAction { get; set; } 84 | 85 | public void Invoke(Progress prog, IList tasks) { 86 | var task = AsyncAction?.Invoke(prog); 87 | Action?.Invoke(prog); 88 | if (task?.IsCompleted == false) 89 | tasks.Add(task); 90 | } 91 | } 92 | 93 | private class ProgressAction : ActionBase 94 | { 95 | public Trigger Trigger { get; set; } 96 | public bool Recurring { get; set; } 97 | } 98 | 99 | private class TimerAction : ActionBase 100 | { 101 | private Timer _timer; 102 | 103 | public TimeSpan Interval { get; set; } 104 | 105 | public void Start(Tracker tracker) { 106 | _timer = new Timer(_ => Invoke(tracker.GetProgress(), tracker._tasks), null, Interval, Interval); 107 | } 108 | 109 | public void Stop() { 110 | _timer.Dispose(); 111 | } 112 | } 113 | } 114 | 115 | public class Trigger 116 | { 117 | private readonly int _targetNumber; 118 | private readonly Func _getCurrentNumber; 119 | private int _nextNumber; 120 | 121 | public Trigger(int targetNumber, Func getCurrentNumber) { 122 | _nextNumber = _targetNumber = targetNumber; 123 | _getCurrentNumber = getCurrentNumber; 124 | } 125 | 126 | public bool IsFired(Progress prog) { 127 | if (_getCurrentNumber(prog) >= _nextNumber) { 128 | _nextNumber += _targetNumber; 129 | return true; 130 | } 131 | return false; 132 | } 133 | } 134 | 135 | public static class TriggerBuilderExtensions 136 | { 137 | public static Trigger ItemsStarted(this int i) => new Trigger(i, p => p.ItemsStarted); 138 | public static Trigger ItemsDone(this int i) => new Trigger(i, p => p.ItemsDone); 139 | public static Trigger ItemsSucceeded(this int i) => new Trigger(i, p => p.ItemsSucceeded); 140 | public static Trigger ItemsFailed(this int i) => new Trigger(i, p => p.ItemsFailed); 141 | 142 | public static Trigger PercentStarted(this int i) => new Trigger(i, p => p.PercentStarted); 143 | public static Trigger PercentDone(this int i) => new Trigger(i, p => p.PercentDone); 144 | public static Trigger PercentSucceeded(this int i) => new Trigger(i, p => p.PercentSucceeded); 145 | public static Trigger PercentFailed(this int i) => new Trigger(i, p => p.PercentFailed); 146 | 147 | public static TimeSpan Seconds(this int i) => TimeSpan.FromSeconds(i); 148 | public static TimeSpan Minutes(this int i) => TimeSpan.FromMinutes(i); 149 | public static TimeSpan Hours(this int i) => TimeSpan.FromHours(i); 150 | } 151 | 152 | public class Progress 153 | { 154 | private readonly long _startTime; 155 | private readonly long _endTime; 156 | 157 | public int TotalItems { get; } 158 | public int ItemsStarted { get; } 159 | public int ItemsSucceeded { get; } 160 | public int ItemsFailed { get; } 161 | 162 | public int ItemsDone => ItemsSucceeded + ItemsFailed; 163 | public int ItemsInProgress => ItemsStarted - ItemsDone; 164 | public int ItemsRemaining => TotalItems - ItemsStarted; 165 | 166 | public int PercentStarted => 100 * ItemsStarted / TotalItems; 167 | public int PercentDone => 100 * ItemsDone / TotalItems; 168 | public int PercentSucceeded => 100 * ItemsSucceeded / TotalItems; 169 | public int PercentFailed => 100 * ItemsFailed / TotalItems; 170 | public int PercentInProgress => 100 * ItemsInProgress / TotalItems; 171 | public int PercentRemaining => 100 * ItemsRemaining / TotalItems; 172 | 173 | public float PercentStartedExact => (float)100 * ItemsStarted / TotalItems; 174 | public float PercentDoneExact => (float)100 * ItemsDone / TotalItems; 175 | public float PercentSucceededExact => (float)100 * ItemsSucceeded / TotalItems; 176 | public float PercentFailedExact => (float)100 * ItemsFailed / TotalItems; 177 | public float PercentInProgressExact => (float)100 * ItemsInProgress / TotalItems; 178 | public float PercentRemainingExact => (float)100 * ItemsRemaining / TotalItems; 179 | 180 | private long ElapsedTicks => (_endTime == 0 ? DateTime.UtcNow.Ticks : _endTime) - _startTime; 181 | 182 | public TimeSpan ElapsedTime => TimeSpan.FromTicks(ElapsedTicks); 183 | public int ElapsedSeconds => (int)ElapsedTime.TotalSeconds; 184 | public int ElapsedMinutes => (int)ElapsedTime.TotalMinutes; 185 | public int ElapsedHours => (int)ElapsedTime.TotalHours; 186 | 187 | public TimeSpan EstTotalTime => TimeSpan.FromTicks(ElapsedTicks * TotalItems / ItemsDone); 188 | public TimeSpan EstTimeRemaining => EstTotalTime - ElapsedTime; 189 | public DateTime EstEndTimeUtc => DateTime.UtcNow + EstTimeRemaining; 190 | public DateTime EstEndTimeLocal => DateTime.Now + EstTimeRemaining; 191 | 192 | public bool IsDone => ItemsDone == TotalItems; 193 | 194 | public Progress(long startTime, long endTime, int total, int started, int succeeded, int failed) { 195 | _startTime = startTime; 196 | _endTime = endTime; 197 | TotalItems = total; 198 | ItemsStarted = started; 199 | ItemsSucceeded = succeeded; 200 | ItemsFailed = failed; 201 | } 202 | } 203 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NProg 2 | 3 | NProg is a general-purpose progress tracking framework for .NET. It is useful in batch processing applications where you want to periodically display, log, or otherwise process overall progress. 4 | 5 | ## Example 6 | 7 | ```C# 8 | using NProg; 9 | 10 | // setup 11 | var tracker = new Tracker(workItems.Count); 12 | tracker.Every(100.ItemsDone(), prog => 13 | Console.WriteLine($"{prog.ItemsDone} items done")); 14 | tracker.Every(10.Seconds(), prog => 15 | Console.WriteLine($"{prog.PercentRemaining}% left to go")); 16 | tracker.On(50.PercentDone(), prog => 17 | Console.WriteLine("Half way, should be done around {prog.EstEndTimeLocal:h:mm tt}")); 18 | tracker.OnComplete(prog => 19 | Console.WriteLine($"Finished in {prog.ElapsedMinutes} minutes")); 20 | 21 | // async actions are also supported, awaitable via tracker.CompleteAsync() 22 | tracker.OnComplete(prog => 23 | LogAsync($"Finished in {prog.ElapsedMinutes} minutes")); 24 | 25 | // run 26 | tracker.Start(); 27 | foreach (var item in workItems) { 28 | tracker.ItemStarted(); 29 | try { 30 | ProcessItem(item); 31 | tracker.ItemSucceeded(); 32 | } 33 | catch (Exception ex) { 34 | tracker.ItemFailed(); 35 | // log exception 36 | } 37 | finally { 38 | // await any asynchronous actions that may have been triggered 39 | await tracker.CompleteAsync(); 40 | } 41 | } 42 | ``` 43 | 44 | Have a look at the [demo](https://github.com/tmenier/NProg/blob/master/NProg.Demo/Program.cs) for a more in-depth example. 45 | 46 | ## Setup 47 | 48 | As the example shows, you set up a tracker by declaring the total item count and creating triggers and actions with the `Every` (periodic) and `On` (one-time) methods. Extension methoods on `int` help you define the triggers: 49 | 50 | ```C# 51 | // triggers based on item count 52 | i.ItemsStarted() 53 | i.ItemsDone() 54 | i.ItemsSucceeded() 55 | i.ItemsFailed() 56 | 57 | // triggers based on percent of total 58 | i.PercentStarted() 59 | i.PercentDone() 60 | i.PercentSucceeded() 61 | i.PercentFailed() 62 | 63 | // triggers based on elapsed time 64 | i.Seconds() 65 | i.Minutes() 66 | i.Hours() 67 | ``` 68 | 69 | The last argument to `Every` and `On` is an `Action`. `Progress` provides a wealth of information useful for displaying, logging, etc: 70 | 71 | ```c# 72 | int TotalItems { get; } 73 | int ItemsStarted { get; } 74 | int ItemsSucceeded { get; } 75 | int ItemsFailed { get; } 76 | 77 | int ItemsDone { get; } // succeeded + failed 78 | int ItemsInProgress { get; } // started - done 79 | int ItemsRemaining { get; } // total - started 80 | bool IsDone { get; } // done == total 81 | 82 | // rounded down 83 | int PercentStarted { get; } 84 | int PercentDone { get; } 85 | int PercentSucceeded { get; } 86 | int PercentFailed { get; } 87 | int PercentInProgress { get; } 88 | int PercentRemaining { get; } 89 | 90 | // more precise 91 | float PercentStartedExact { get; } 92 | float PercentDoneExact { get; } 93 | float PercentSucceededExact { get; } 94 | float PercentFailedExact { get; } 95 | float PercentInProgressExact { get; } 96 | float PercentRemainingExact { get; } 97 | 98 | // elapsed time 99 | TimeSpan ElapsedTime { get; } 100 | int ElapsedSeconds { get; } 101 | int ElapsedMinutes { get; } 102 | int ElapsedHours { get; } 103 | 104 | // completion time estimates 105 | TimeSpan EstTotalTime { get; } 106 | TimeSpan EstTimeRemaining { get; } 107 | DateTime EstEndTimeUtc { get; } 108 | DateTime EstEndTimeLocal { get; } 109 | ``` 110 | 111 | ## Run 112 | 113 | Referring again to the example, `Start`, `ItemStarted`, `ItemSucceeded`, `ItemFailed`, and `Stop` are the main methods you will call on `Tracker` during the course of a batch job. 114 | 115 | `Start` and `Stop` are optional. For time tracking, `Progress` defaults to when the `Tracker` was created and when the last item was completed for its elapsed time calculations, but you can call these methods if you want more precise control over those values. 116 | 117 | `ItemStarted`, `ItemSucceeded`, `ItemFailed` are all thread-safe. In concurrent environments, you can call them on the same `Tracker` instance from multiple threads without conflicts such as the same trigger firing twice. `ItemStarted` is optional if you only want to track "done" items and not "started" or "in progress". 118 | 119 | ## Get it 120 | 121 | This project is brand new and still in the experimental phase. It is not available on NuGet (yet), but for convenience it is completely contained in a single C# file that you can drop into your project. Get it [here](https://raw.githubusercontent.com/tmenier/NProg/master/NProg/Tracker.cs). 122 | 123 | ## Questions? Feedback? 124 | 125 | Like it? Hate it? Found a bug? Got a feature request? Did I reinvent something that already exists? Got a better name for this thing? For time being I welcome any and all feedback under [issues](https://github.com/tmenier/NProg/issues). 126 | --------------------------------------------------------------------------------