├── .github
└── workflows
│ ├── benchmark.yml
│ └── dotnet.yml
├── .gitignore
├── .idea
└── .idea.AsyncSemaphore
│ └── .idea
│ ├── .gitignore
│ ├── encodings.xml
│ ├── indexLayout.xml
│ └── vcs.xml
├── AsyncSemaphore.Analyzers
├── AsyncSemaphore.Analyzers.Tests
│ ├── AsyncSemaphore.Analyzers.Tests.csproj
│ ├── AsyncSemaphoreAnalyzerTests.cs
│ ├── AsyncSemaphoreReleaserAnalyzerTests.cs
│ └── Verifiers
│ │ ├── CSharpAnalyzerVerifier.cs
│ │ ├── CSharpAnalyzerVerifier`1.cs
│ │ └── CSharpVerifierHelper.cs
└── AsyncSemaphore.Analyzers
│ ├── AnalyzerReleases.Shipped.md
│ ├── AnalyzerReleases.Unshipped.md
│ ├── AsyncSemaphore.Analyzers.csproj
│ ├── AsyncSemaphoreAnalyzer.cs
│ ├── AsyncSemaphoreReleaserAnalyzer.cs
│ ├── Properties
│ └── launchSettings.json
│ ├── Readme.md
│ ├── Resources.Designer.cs
│ ├── Resources.resx
│ └── Rules.cs
├── AsyncSemaphore.Benchmark
├── AsyncSemaphore.Benchmark.csproj
├── Benchmarks.cs
└── Program.cs
├── AsyncSemaphore.Pipeline
├── AsyncSemaphore.Pipeline.csproj
├── Modules
│ ├── LocalMachine
│ │ ├── AddLocalNugetSourceModule.cs
│ │ ├── CreateLocalNugetFolderModule.cs
│ │ └── UploadPackagesToLocalNuGetModule.cs
│ ├── NugetVersionGeneratorModule.cs
│ ├── PackProjectsModule.cs
│ ├── PackageFilesRemovalModule.cs
│ ├── PackagePathsModule.cs
│ ├── RunUnitTestsModule.cs
│ └── UploadPackagesToNugetModule.cs
├── Program.cs
├── Settings
│ └── NuGetSettings.cs
└── appsettings.json
├── AsyncSemaphore.UnitTests
├── AsyncSemaphore.UnitTests.csproj
└── Tests.cs
├── AsyncSemaphore.sln
├── AsyncSemaphore
├── AsyncSemaphore.cs
├── AsyncSemaphore.csproj
├── AsyncSemaphoreReleaser.cs
└── IAsyncSemaphore.cs
├── Directory.Build.props
├── LICENSE
├── NuGet.config
├── README.md
├── global.json
└── renovate.json
/.github/workflows/benchmark.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a .NET project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
3 |
4 | name: Benchmarks
5 |
6 | on:
7 | workflow_dispatch:
8 | inputs:
9 |
10 | jobs:
11 | benchmark:
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v4
16 | with:
17 | fetch-depth: 0
18 | persist-credentials: false
19 | - name: Setup .NET
20 | uses: actions/setup-dotnet@v4
21 | with:
22 | dotnet-version: 9.0.x
23 | - name: Run Benchmark
24 | run: dotnet run -c Release
25 | working-directory: "AsyncSemaphore.Benchmark"
--------------------------------------------------------------------------------
/.github/workflows/dotnet.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a .NET project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
3 |
4 | name: .NET
5 |
6 | on:
7 | push:
8 | branches: ["main"]
9 | pull_request:
10 | branches: ["main"]
11 | workflow_dispatch:
12 | inputs:
13 | publish-packages:
14 | description: Publish packages?
15 | type: boolean
16 | required: true
17 |
18 | jobs:
19 | modularpipeline:
20 | environment: ${{ github.ref == 'refs/heads/main' && 'Production' || 'Pull Requests' }}
21 | runs-on: ubuntu-latest
22 |
23 | steps:
24 | - uses: actions/checkout@v4
25 | with:
26 | fetch-depth: 0
27 | persist-credentials: false
28 | - name: Setup .NET
29 | uses: actions/setup-dotnet@v4
30 | with:
31 | dotnet-version: 9.0.x
32 | - name: Run Pipeline
33 | run: dotnet run -c Release
34 | working-directory: "AsyncSemaphore.Pipeline"
35 | env:
36 | DOTNET_ENVIRONMENT: ${{ github.ref == 'refs/heads/main' && 'Production' || 'Development' }}
37 | NuGet__ApiKey: ${{ github.ref == 'refs/heads/main' && secrets.NUGET__APIKEY || null }}
38 | PULL_REQUEST_BRANCH: ${{ github.event.pull_request.head.ref }}
39 | PUBLISH_PACKAGES: ${{ github.event.inputs.publish-packages }}
40 |
--------------------------------------------------------------------------------
/.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/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
--------------------------------------------------------------------------------
/.idea/.idea.AsyncSemaphore/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Rider ignored files
5 | /projectSettingsUpdater.xml
6 | /.idea.AsyncSemaphore.iml
7 | /modules.xml
8 | /contentModel.xml
9 | # Editor-based HTTP Client requests
10 | /httpRequests/
11 | # Datasource local storage ignored files
12 | /dataSources/
13 | /dataSources.local.xml
14 |
--------------------------------------------------------------------------------
/.idea/.idea.AsyncSemaphore/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/.idea.AsyncSemaphore/.idea/indexLayout.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/.idea.AsyncSemaphore/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.Tests/AsyncSemaphore.Analyzers.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net9.0
5 | enable
6 |
7 | false
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.Tests/AsyncSemaphoreAnalyzerTests.cs:
--------------------------------------------------------------------------------
1 | using Semaphores.Analyzers;
2 | using Verifier = AsyncSemaphore.Analyzers.Tests.Verifiers.CSharpAnalyzerVerifier;
3 |
4 | namespace AsyncSemaphore.Analyzers.Tests;
5 |
6 | public class AsyncSemaphoreAnalyzerTests
7 | {
8 | [Test]
9 | public async Task Must_Await_Analyzer()
10 | {
11 | const string text = @"
12 | using Semaphores;
13 |
14 | public class Program
15 | {
16 | public void Main()
17 | {
18 | var semaphore = new AsyncSemaphore(1);
19 | {|#0:semaphore.WaitAsync();|}
20 | }
21 | }
22 | ";
23 |
24 | var expected = Verifier.Diagnostic(Rules.AwaitRule).WithLocation(0);
25 |
26 | await Verifier.VerifyAnalyzerAsync(text, expected);
27 | }
28 |
29 | [Test]
30 | public async Task Must_Assign_Variable_Analyzer()
31 | {
32 | const string text = @"
33 | using System.Threading.Tasks;
34 | using Semaphores;
35 |
36 | public class Program
37 | {
38 | public async Task Main()
39 | {
40 | var semaphore = new AsyncSemaphore(1);
41 | {|#0:await semaphore.WaitAsync();|}
42 | }
43 | }
44 | ";
45 |
46 | var expected = Verifier.Diagnostic(Rules.VariableAssignmentRule).WithLocation(0);
47 |
48 | await Verifier.VerifyAnalyzerAsync(text, expected);
49 | }
50 |
51 | [Test]
52 | public async Task Must_Use_Using_Keyword_Analyzer()
53 | {
54 | const string text = @"
55 | using System.Threading.Tasks;
56 | using Semaphores;
57 |
58 | public class Program
59 | {
60 | public async Task Main()
61 | {
62 | var semaphore = new AsyncSemaphore(1);
63 | {|#0:var lockHandle = await semaphore.WaitAsync();|}
64 | }
65 | }
66 | ";
67 |
68 | var expected = Verifier.Diagnostic(Rules.UsingKeywordRule).WithLocation(0);
69 |
70 | await Verifier.VerifyAnalyzerAsync(text, expected);
71 | }
72 |
73 | [Test]
74 | public async Task No_Error_Flagged()
75 | {
76 | const string text = @"
77 | using System.Threading.Tasks;
78 | using Semaphores;
79 |
80 | public class Program
81 | {
82 | public async Task Main()
83 | {
84 | var semaphore = new AsyncSemaphore(1);
85 | {|#0:using var lockHandle = await semaphore.WaitAsync();|}
86 | }
87 | }
88 | ";
89 |
90 | await Verifier.VerifyAnalyzerAsync(text);
91 | }
92 |
93 | [Test]
94 | public async Task No_Error_Flagged_When_Scoped()
95 | {
96 | const string text = @"
97 | using System.Threading.Tasks;
98 | using Semaphores;
99 |
100 | public class Program
101 | {
102 | public async Task Main()
103 | {
104 | var semaphore = new AsyncSemaphore(1);
105 | using (await semaphore.WaitAsync())
106 | {
107 | }
108 | }
109 | }
110 | ";
111 |
112 | await Verifier.VerifyAnalyzerAsync(text);
113 | }
114 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.Tests/AsyncSemaphoreReleaserAnalyzerTests.cs:
--------------------------------------------------------------------------------
1 | using Semaphores.Analyzers;
2 | using Verifier = AsyncSemaphore.Analyzers.Tests.Verifiers.CSharpAnalyzerVerifier;
3 |
4 | namespace AsyncSemaphore.Analyzers.Tests;
5 |
6 | public class AsyncSemaphoreReleaserAnalyzerTests
7 | {
8 | [Test]
9 | public async Task Do_Not_Dispose_Explicitly_Warning()
10 | {
11 | const string text = @"
12 | using System.Threading.Tasks;
13 | using Semaphores;
14 |
15 | public class Program
16 | {
17 | public async Task Main()
18 | {
19 | var semaphore = new AsyncSemaphore(1);
20 | using var lockHandle = await semaphore.WaitAsync();
21 | {|#0:lockHandle.Dispose()|};
22 | }
23 | }
24 | ";
25 |
26 | var expected = Verifier.Diagnostic(Rules.DoNotDisposeExplicitlyRule).WithLocation(0);
27 |
28 | await Verifier.VerifyAnalyzerAsync(text, expected);
29 | }
30 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.Tests/Verifiers/CSharpAnalyzerVerifier.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis.CSharp;
2 | using Microsoft.CodeAnalysis.CSharp.Testing;
3 | using Microsoft.CodeAnalysis.Diagnostics;
4 | using Microsoft.CodeAnalysis.Testing;
5 |
6 | namespace AsyncSemaphore.Analyzers.Tests.Verifiers;
7 |
8 | public static partial class CSharpAnalyzerVerifier
9 | where TAnalyzer : DiagnosticAnalyzer, new()
10 | {
11 | public class Test : CSharpAnalyzerTest
12 | {
13 | public Test()
14 | {
15 | ReferenceAssemblies.AddAssemblies(ReferenceAssemblies.Net.Net60.Assemblies);
16 | SolutionTransforms.Add((solution, projectId) =>
17 | {
18 | var project = solution.GetProject(projectId);
19 |
20 | if (project is null)
21 | {
22 | return solution;
23 | }
24 |
25 | var compilationOptions = project.CompilationOptions;
26 |
27 | if (compilationOptions is null)
28 | {
29 | return solution;
30 | }
31 |
32 | if (project.ParseOptions is not CSharpParseOptions parseOptions)
33 | {
34 | return solution;
35 | }
36 |
37 | compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings));
38 |
39 | solution = solution.WithProjectCompilationOptions(projectId, compilationOptions)
40 | .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview));
41 |
42 | return solution;
43 | });
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.Tests/Verifiers/CSharpAnalyzerVerifier`1.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 | using Microsoft.CodeAnalysis.CSharp.Testing;
3 | using Microsoft.CodeAnalysis.Diagnostics;
4 | using Microsoft.CodeAnalysis.Testing;
5 |
6 | namespace AsyncSemaphore.Analyzers.Tests.Verifiers;
7 |
8 | public static partial class CSharpAnalyzerVerifier
9 | where TAnalyzer : DiagnosticAnalyzer, new()
10 | {
11 | ///
12 | public static DiagnosticResult Diagnostic()
13 | => CSharpAnalyzerVerifier.Diagnostic();
14 |
15 | ///
16 | public static DiagnosticResult Diagnostic(string diagnosticId)
17 | => CSharpAnalyzerVerifier.Diagnostic(diagnosticId);
18 |
19 | ///
20 | public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
21 | => CSharpAnalyzerVerifier.Diagnostic(descriptor);
22 |
23 | ///
24 | public static async Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
25 | {
26 | var test = new Test
27 | {
28 | TestCode = source,
29 | ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
30 | TestState =
31 | {
32 | AdditionalReferences =
33 | {
34 | typeof(Semaphores.AsyncSemaphore).Assembly.Location
35 | },
36 | },
37 | };
38 |
39 | test.ExpectedDiagnostics.AddRange(expected);
40 | await test.RunAsync(CancellationToken.None);
41 | }
42 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.Tests/Verifiers/CSharpVerifierHelper.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Immutable;
2 | using Microsoft.CodeAnalysis;
3 | using Microsoft.CodeAnalysis.CSharp;
4 |
5 | namespace AsyncSemaphore.Analyzers.Tests.Verifiers;
6 |
7 | internal static class CSharpVerifierHelper
8 | {
9 | ///
10 | /// By default, the compiler reports diagnostics for nullable reference types at
11 | /// , and the analyzer test framework defaults to only validating
12 | /// diagnostics at . This map contains all compiler diagnostic IDs
13 | /// related to nullability mapped to , which is then used to enable all
14 | /// of these warnings for default validation during analyzer and code fix tests.
15 | ///
16 | internal static ImmutableDictionary NullableWarnings { get; } = GetNullableWarningsFromCompiler();
17 |
18 | private static ImmutableDictionary GetNullableWarningsFromCompiler()
19 | {
20 | string[] args = { "/warnaserror:nullable", "-p:LangVersion=preview" };
21 | var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory);
22 | var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions;
23 |
24 | // Workaround for https://github.com/dotnet/roslyn/issues/41610
25 | nullableWarnings = nullableWarnings
26 | .SetItem("CS8632", ReportDiagnostic.Error)
27 | .SetItem("CS8669", ReportDiagnostic.Error)
28 | .SetItem("CS8652", ReportDiagnostic.Suppress);
29 |
30 | return nullableWarnings;
31 | }
32 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/AnalyzerReleases.Shipped.md:
--------------------------------------------------------------------------------
1 | ## Release 1.0
2 |
3 | ### New Rules
4 |
5 | Rule ID | Category | Severity | Notes
6 | --------|----------|----------|--------------------------------------------------
7 | SEM0001 | Usage | Warning | WaitAsync should be awaited.
8 | SEM0002 | Usage | Warning | The lock should be assigned to a variable.
9 | SEM0003 | Usage | Warning | The using keyword should be used to automatically release the lock.
10 | SEM0004 | Usage | Warning | The releaser's Dispose method should not be called explicitly.
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/AnalyzerReleases.Unshipped.md:
--------------------------------------------------------------------------------
1 | ### New Rules
2 |
3 | Rule ID | Category | Severity | Notes
4 | --------|----------|----------|-------
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | false
6 | enable
7 | latest
8 |
9 | true
10 | true
11 |
12 | Semaphores.Analyzers
13 | AsyncSemaphore.Analyzers
14 |
15 | true
16 |
17 | RS2003
18 |
19 |
20 |
21 |
22 | all
23 | runtime; build; native; contentfiles; analyzers; buildtransitive
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | ResXFileCodeGenerator
32 | Resources.Designer.cs
33 |
34 |
35 |
36 |
37 |
38 | True
39 | True
40 | Resources.resx
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/AsyncSemaphoreAnalyzer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Immutable;
2 | using Microsoft.CodeAnalysis;
3 | using Microsoft.CodeAnalysis.CSharp;
4 | using Microsoft.CodeAnalysis.CSharp.Syntax;
5 | using Microsoft.CodeAnalysis.Diagnostics;
6 | using Microsoft.CodeAnalysis.Operations;
7 |
8 | namespace Semaphores.Analyzers;
9 |
10 | [DiagnosticAnalyzer(LanguageNames.CSharp)]
11 | public class AsyncSemaphoreAnalyzer : DiagnosticAnalyzer
12 | {
13 | private const string CommonApiClassName = "AsyncSemaphore";
14 | private const string CommonApiMethodName = "WaitAsync";
15 |
16 | public override ImmutableArray SupportedDiagnostics { get; } =
17 | ImmutableArray.Create(Rules.AwaitRule, Rules.VariableAssignmentRule, Rules.UsingKeywordRule);
18 |
19 | public override void Initialize(AnalysisContext context)
20 | {
21 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
22 | context.EnableConcurrentExecution();
23 | context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation);
24 | }
25 |
26 | ///
27 | /// Executed on the completion of the semantic analysis associated with the Invocation operation.
28 | ///
29 | /// Operation context.
30 | private void AnalyzeOperation(OperationAnalysisContext context)
31 | {
32 | if (context.Operation is not IInvocationOperation invocationOperation ||
33 | context.Operation.Syntax is not InvocationExpressionSyntax invocationSyntax)
34 | {
35 | return;
36 | }
37 |
38 | var methodSymbol = invocationOperation.TargetMethod;
39 |
40 | if (methodSymbol.MethodKind != MethodKind.Ordinary ||
41 | methodSymbol.ReceiverType?.Name != CommonApiClassName ||
42 | methodSymbol.Name != CommonApiMethodName
43 | )
44 | {
45 | return;
46 | }
47 |
48 | var parentStatement = GetParentStatement(invocationSyntax);
49 |
50 | var descendantNodes = parentStatement.DescendantNodes().ToList();
51 | var descendantTokens = parentStatement.DescendantTokens().ToList();
52 |
53 | if (!descendantNodes.Any(x => x is AwaitExpressionSyntax))
54 | {
55 | context.ReportDiagnostic(Diagnostic.Create(Rules.AwaitRule,
56 | parentStatement.GetLocation()));
57 | return;
58 | }
59 |
60 | if (descendantTokens.Any(x => x.IsKind(SyntaxKind.UsingKeyword)))
61 | {
62 | // We're correct disposing it on scope exit
63 | return;
64 | }
65 |
66 | if (!descendantNodes.Any(x => x is VariableDeclarationSyntax))
67 | {
68 | context.ReportDiagnostic(Diagnostic.Create(Rules.VariableAssignmentRule,
69 | parentStatement.GetLocation()));
70 | return;
71 | }
72 |
73 | context.ReportDiagnostic(Diagnostic.Create(Rules.UsingKeywordRule,
74 | parentStatement.GetLocation()));
75 | }
76 |
77 | private static SyntaxNode GetParentStatement(InvocationExpressionSyntax invocationSyntax)
78 | {
79 | var parent = invocationSyntax.Parent;
80 |
81 | while (parent is not StatementSyntax)
82 | {
83 | parent = parent?.Parent;
84 | }
85 |
86 | return parent;
87 | }
88 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/AsyncSemaphoreReleaserAnalyzer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Immutable;
2 | using Microsoft.CodeAnalysis;
3 | using Microsoft.CodeAnalysis.CSharp.Syntax;
4 | using Microsoft.CodeAnalysis.Diagnostics;
5 | using Microsoft.CodeAnalysis.Operations;
6 |
7 | namespace Semaphores.Analyzers;
8 |
9 | ///
10 | /// A sample analyzer that reports invalid values being used for the 'speed' parameter of the 'SetSpeed' function.
11 | /// To make sure that we analyze the method of the specific class, we use semantic analysis instead of the syntax tree, so this analyzer will not work if the project is not compilable.
12 | ///
13 | [DiagnosticAnalyzer(LanguageNames.CSharp)]
14 | public class AsyncSemaphoreReleaserAnalyzer : DiagnosticAnalyzer
15 | {
16 | private const string CommonApiClassName = "AsyncSemaphoreReleaser";
17 | private const string CommonApiMethodName = "Dispose";
18 |
19 | public override ImmutableArray SupportedDiagnostics { get; } =
20 | ImmutableArray.Create(Rules.DoNotDisposeExplicitlyRule);
21 |
22 | public override void Initialize(AnalysisContext context)
23 | {
24 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
25 | context.EnableConcurrentExecution();
26 | context.RegisterOperationAction(AnalyzeOperation, OperationKind.Invocation);
27 | }
28 |
29 | ///
30 | /// Executed on the completion of the semantic analysis associated with the Invocation operation.
31 | ///
32 | /// Operation context.
33 | private void AnalyzeOperation(OperationAnalysisContext context)
34 | {
35 | if (context.Operation is not IInvocationOperation invocationOperation ||
36 | context.Operation.Syntax is not InvocationExpressionSyntax invocationSyntax)
37 | {
38 | return;
39 | }
40 |
41 | var methodSymbol = invocationOperation.TargetMethod;
42 |
43 | if (methodSymbol.MethodKind != MethodKind.Ordinary ||
44 | methodSymbol.ReceiverType?.Name != CommonApiClassName ||
45 | methodSymbol.Name != CommonApiMethodName
46 | )
47 | {
48 | return;
49 | }
50 |
51 | context.ReportDiagnostic(Diagnostic.Create(Rules.DoNotDisposeExplicitlyRule, invocationSyntax.GetLocation()));
52 | }
53 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/launchsettings.json",
3 | "profiles": {
4 | "DebugRoslynAnalyzers": {
5 | "commandName": "DebugRoslynComponent",
6 | "targetProject": "../AsyncSemaphore.Analyzers.Sample/AsyncSemaphore.Analyzers.Sample.csproj"
7 | }
8 | }
9 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/Readme.md:
--------------------------------------------------------------------------------
1 | # Roslyn Analyzers Sample
2 |
3 | A set of three sample projects that includes Roslyn analyzers with code fix providers. Enjoy this template to learn from and modify analyzers for your own needs.
4 |
5 | ## Content
6 | ### AsyncSemaphore.Analyzers
7 | A .NET Standard project with implementations of sample analyzers and code fix providers.
8 | **You must build this project to see the results (warnings) in the IDE.**
9 |
10 | - [SampleSemanticAnalyzer.cs](SampleSemanticAnalyzer.cs): An analyzer that reports invalid values used for the `speed` parameter of the `SetSpeed` function.
11 | - [SampleSyntaxAnalyzer.cs](SampleSyntaxAnalyzer.cs): An analyzer that reports the company name used in class definitions.
12 | - [SampleCodeFixProvider.cs](SampleCodeFixProvider.cs): A code fix that renames classes with company name in their definition. The fix is linked to [SampleSyntaxAnalyzer.cs](SampleSyntaxAnalyzer.cs).
13 |
14 | ### AsyncSemaphore.Analyzers.Sample
15 | A project that references the sample analyzers. Note the parameters of `ProjectReference` in [AsyncSemaphore.Analyzers.Sample.csproj](../AsyncSemaphore.Analyzers.Sample/AsyncSemaphore.Analyzers.Sample.csproj), they make sure that the project is referenced as a set of analyzers.
16 |
17 | ### AsyncSemaphore.Analyzers.Tests
18 | Unit tests for the sample analyzers and code fix provider. The easiest way to develop language-related features is to start with unit tests.
19 |
20 | ## How To?
21 | ### How to debug?
22 | - Use the [launchSettings.json](Properties/launchSettings.json) profile.
23 | - Debug tests.
24 |
25 | ### How can I determine which syntax nodes I should expect?
26 | Consider installing the Roslyn syntax tree viewer plugin [Rossynt](https://plugins.jetbrains.com/plugin/16902-rossynt/).
27 |
28 | ### Learn more about wiring analyzers
29 | The complete set of information is available at [roslyn github repo wiki](https://github.com/dotnet/roslyn/blob/main/docs/wiki/README.md).
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | //
5 | // Changes to this file may cause incorrect behavior and will be lost if
6 | // the code is regenerated.
7 | //
8 | //------------------------------------------------------------------------------
9 |
10 | namespace Semaphores.Analyzers {
11 | ///
12 | /// A strongly-typed resource class, for looking up localized strings, etc.
13 | ///
14 | // This class was auto-generated by the StronglyTypedResourceBuilder
15 | // class via a tool like ResGen or Visual Studio.
16 | // To add or remove a member, edit your .ResX file then rerun ResGen
17 | // with the /str option, or rebuild your VS project.
18 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
19 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
20 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
21 | internal class Resources {
22 |
23 | private static global::System.Resources.ResourceManager resourceMan;
24 |
25 | private static global::System.Globalization.CultureInfo resourceCulture;
26 |
27 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
28 | internal Resources() {
29 | }
30 |
31 | ///
32 | /// Returns the cached ResourceManager instance used by this class.
33 | ///
34 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
35 | internal static global::System.Resources.ResourceManager ResourceManager {
36 | get {
37 | if (object.ReferenceEquals(resourceMan, null)) {
38 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Semaphores.Analyzers.Resources", typeof(Resources).Assembly);
39 | resourceMan = temp;
40 | }
41 | return resourceMan;
42 | }
43 | }
44 |
45 | ///
46 | /// Overrides the current thread's CurrentUICulture property for all
47 | /// resource lookups using this strongly typed resource class.
48 | ///
49 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
50 | internal static global::System.Globalization.CultureInfo Culture {
51 | get {
52 | return resourceCulture;
53 | }
54 | set {
55 | resourceCulture = value;
56 | }
57 | }
58 |
59 | ///
60 | /// Looks up a localized string similar to Await Method.
61 | ///
62 | internal static string SEM0001CodeFixTitle {
63 | get {
64 | return ResourceManager.GetString("SEM0001CodeFixTitle", resourceCulture);
65 | }
66 | }
67 |
68 | ///
69 | /// Looks up a localized string similar to Must await WaitAsync..
70 | ///
71 | internal static string SEM0001Description {
72 | get {
73 | return ResourceManager.GetString("SEM0001Description", resourceCulture);
74 | }
75 | }
76 |
77 | ///
78 | /// Looks up a localized string similar to Must await WaitAsync.
79 | ///
80 | internal static string SEM0001MessageFormat {
81 | get {
82 | return ResourceManager.GetString("SEM0001MessageFormat", resourceCulture);
83 | }
84 | }
85 |
86 | ///
87 | /// Looks up a localized string similar to Must await WaitAsync.
88 | ///
89 | internal static string SEM0001Title {
90 | get {
91 | return ResourceManager.GetString("SEM0001Title", resourceCulture);
92 | }
93 | }
94 |
95 | ///
96 | /// Looks up a localized string similar to Must assign lock handle to variable..
97 | ///
98 | internal static string SEM0002Description {
99 | get {
100 | return ResourceManager.GetString("SEM0002Description", resourceCulture);
101 | }
102 | }
103 |
104 | ///
105 | /// Looks up a localized string similar to Must assign lock handle to variable.
106 | ///
107 | internal static string SEM0002MessageFormat {
108 | get {
109 | return ResourceManager.GetString("SEM0002MessageFormat", resourceCulture);
110 | }
111 | }
112 |
113 | ///
114 | /// Looks up a localized string similar to Must assign lock handle to variable.
115 | ///
116 | internal static string SEM0002Title {
117 | get {
118 | return ResourceManager.GetString("SEM0002Title", resourceCulture);
119 | }
120 | }
121 |
122 | ///
123 | /// Looks up a localized string similar to Must use `using` keyword on lock handle..
124 | ///
125 | internal static string SEM0003Description {
126 | get {
127 | return ResourceManager.GetString("SEM0003Description", resourceCulture);
128 | }
129 | }
130 |
131 | ///
132 | /// Looks up a localized string similar to Must use `using` keyword on lock handle.
133 | ///
134 | internal static string SEM0003MessageFormat {
135 | get {
136 | return ResourceManager.GetString("SEM0003MessageFormat", resourceCulture);
137 | }
138 | }
139 |
140 | ///
141 | /// Looks up a localized string similar to Must use `using` keyword on lock handle.
142 | ///
143 | internal static string SEM0003Title {
144 | get {
145 | return ResourceManager.GetString("SEM0003Title", resourceCulture);
146 | }
147 | }
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | text/microsoft-resx
11 |
12 |
13 | 1.3
14 |
15 |
16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
17 |
18 |
19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
20 |
21 |
22 | Must await WaitAsync.
23 |
24 |
25 | Must await WaitAsync
26 |
27 |
28 | Must await WaitAsync
29 |
30 |
31 | Await Method
32 |
33 |
34 | Must assign lock handle to variable.
35 |
36 |
37 | Must assign lock handle to variable
38 |
39 |
40 | Must assign lock handle to variable
41 |
42 |
43 | Must use `using` keyword on lock handle.
44 |
45 |
46 | Must use `using` keyword on lock handle
47 |
48 |
49 | Must use `using` keyword on lock handle
50 |
51 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Analyzers/AsyncSemaphore.Analyzers/Rules.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.CodeAnalysis;
2 |
3 | namespace Semaphores.Analyzers;
4 |
5 | public class Rules
6 | {
7 | public static DiagnosticDescriptor AwaitRule => Create("SEM0001");
8 | public static DiagnosticDescriptor VariableAssignmentRule => Create("SEM0002");
9 | public static DiagnosticDescriptor UsingKeywordRule => Create("SEM0003");
10 | public static DiagnosticDescriptor DoNotDisposeExplicitlyRule => Create("SEM0004");
11 |
12 | public static DiagnosticDescriptor Create(string diagnosticId)
13 | {
14 | var messageFormat = new LocalizableResourceString(diagnosticId + "MessageFormat",
15 | Resources.ResourceManager,
16 | typeof(Resources));
17 |
18 | var title = new LocalizableResourceString(diagnosticId + "Title",
19 | Resources.ResourceManager,
20 | typeof(Resources));
21 |
22 | var description = new LocalizableResourceString(diagnosticId + "Description",
23 | Resources.ResourceManager,
24 | typeof(Resources));
25 |
26 | return new(diagnosticId, title, messageFormat, "Usage",
27 | DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
28 | }
29 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Benchmark/AsyncSemaphore.Benchmark.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net9.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Benchmark/Benchmarks.cs:
--------------------------------------------------------------------------------
1 | using BenchmarkDotNet.Attributes;
2 | using BenchmarkDotNet.Jobs;
3 |
4 | namespace AsyncSemaphore.Benchmark;
5 |
6 | [MemoryDiagnoser]
7 | public class Benchmarks
8 | {
9 | private readonly SemaphoreSlim _semaphoreSlim = new(1, 1);
10 | private readonly Semaphores.AsyncSemaphore _asyncSemaphore = new(1);
11 |
12 | [Benchmark]
13 | public async Task Raw_Semaphore_Slim()
14 | {
15 | try
16 | {
17 | await _semaphoreSlim.WaitAsync();
18 | }
19 | finally
20 | {
21 | _semaphoreSlim.Release();
22 | }
23 | }
24 |
25 | [Benchmark]
26 | public async Task AsyncSemaphore_With_Inherited_Scope()
27 | {
28 | using var _ = await _asyncSemaphore.WaitAsync();
29 | }
30 |
31 | [Benchmark]
32 | public async Task AsyncSemaphore_With_Braced_Scope()
33 | {
34 | using (await _asyncSemaphore.WaitAsync())
35 | {
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Benchmark/Program.cs:
--------------------------------------------------------------------------------
1 | using AsyncSemaphore.Benchmark;
2 | using BenchmarkDotNet.Running;
3 |
4 | var summary = BenchmarkRunner.Run();
5 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/AsyncSemaphore.Pipeline.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net9.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/LocalMachine/AddLocalNugetSourceModule.cs:
--------------------------------------------------------------------------------
1 | using ModularPipelines.Attributes;
2 | using ModularPipelines.Context;
3 | using ModularPipelines.DotNet.Extensions;
4 | using ModularPipelines.DotNet.Options;
5 | using ModularPipelines.Exceptions;
6 | using ModularPipelines.Models;
7 | using ModularPipelines.Modules;
8 |
9 | namespace AsyncSemaphore.Pipeline.Modules.LocalMachine;
10 |
11 | [DependsOn]
12 | public class AddLocalNugetSourceModule : Module
13 | {
14 | protected override async Task ShouldIgnoreFailures(IPipelineContext context, Exception exception)
15 | {
16 | await Task.Yield();
17 | return exception is CommandException commandException &&
18 | commandException.StandardOutput.Contains("The name specified has already been added to the list of available package sources");
19 | }
20 |
21 | protected override async Task ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
22 | {
23 | var localNugetPathResult = await GetModule();
24 |
25 | return await context.DotNet().Nuget.Add
26 | .Source(new DotNetNugetAddSourceOptions(localNugetPathResult.Value!)
27 | {
28 | Name = "ModularPipelinesLocalNuGet"
29 | }, cancellationToken);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/LocalMachine/CreateLocalNugetFolderModule.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Logging;
2 | using ModularPipelines.Attributes;
3 | using ModularPipelines.Context;
4 | using ModularPipelines.FileSystem;
5 | using ModularPipelines.Modules;
6 |
7 | namespace AsyncSemaphore.Pipeline.Modules.LocalMachine;
8 |
9 | [DependsOn]
10 | [DependsOn]
11 | public class CreateLocalNugetFolderModule : Module
12 | {
13 | protected override async Task ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
14 | {
15 | var localNugetRepositoryFolder = context.FileSystem.GetFolder(Environment.SpecialFolder.ApplicationData)
16 | .GetFolder("ModularPipelines")
17 | .GetFolder("LocalNuget")
18 | .Create();
19 |
20 | await Task.Yield();
21 |
22 | context.Logger.LogInformation("Local NuGet Repository Path: {Path}", localNugetRepositoryFolder.Path);
23 |
24 | return localNugetRepositoryFolder;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/LocalMachine/UploadPackagesToLocalNuGetModule.cs:
--------------------------------------------------------------------------------
1 | using EnumerableAsyncProcessor.Extensions;
2 | using Microsoft.Extensions.Logging;
3 | using ModularPipelines.Attributes;
4 | using ModularPipelines.Context;
5 | using ModularPipelines.DotNet.Extensions;
6 | using ModularPipelines.DotNet.Options;
7 | using ModularPipelines.Models;
8 | using ModularPipelines.Modules;
9 |
10 | namespace AsyncSemaphore.Pipeline.Modules.LocalMachine;
11 |
12 | [DependsOn]
13 | [DependsOn]
14 | [DependsOn]
15 | public class UploadPackagesToLocalNuGetModule : Module
16 | {
17 | protected override async Task OnBeforeExecute(IPipelineContext context)
18 | {
19 | var packagePaths = await GetModule();
20 | foreach (var packagePath in packagePaths.Value!)
21 | {
22 | context.Logger.LogInformation("[Local Directory] Uploading {File}", packagePath);
23 | }
24 |
25 | await base.OnBeforeExecute(context);
26 | }
27 |
28 | protected override async Task ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
29 | {
30 | var localRepoLocation = await GetModule();
31 | var packagePaths = await GetModule();
32 | return await packagePaths.Value!.SelectAsync(async file => await context.DotNet()
33 | .Nuget
34 | .Push(new DotNetNugetPushOptions(file)
35 | {
36 | Source = localRepoLocation.Value!,
37 | }, cancellationToken), cancellationToken: cancellationToken).ProcessOneAtATime();
38 | }
39 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/NugetVersionGeneratorModule.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Logging;
2 | using ModularPipelines.Context;
3 | using ModularPipelines.Git.Extensions;
4 | using ModularPipelines.Modules;
5 |
6 | // ReSharper disable HeuristicUnreachableCode
7 | #pragma warning disable CS0162
8 |
9 | namespace AsyncSemaphore.Pipeline.Modules;
10 |
11 | public class NugetVersionGeneratorModule : Module
12 | {
13 | protected override async Task ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
14 | {
15 | var gitVersionInformation = await context.Git().Versioning.GetGitVersioningInformation();
16 |
17 | if (gitVersionInformation.BranchName == "main")
18 | {
19 | return gitVersionInformation.SemVer!;
20 | }
21 |
22 | return $"{gitVersionInformation.Major}.{gitVersionInformation.Minor}.{gitVersionInformation.Patch}-{gitVersionInformation.PreReleaseLabel}-{gitVersionInformation.CommitsSinceVersionSource}";
23 | }
24 |
25 | protected override async Task OnAfterExecute(IPipelineContext context)
26 | {
27 | var moduleResult = await this;
28 | context.Logger.LogInformation("NuGet Version to Package: {Version}", moduleResult.Value);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/PackProjectsModule.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Logging;
2 | using ModularPipelines.Attributes;
3 | using ModularPipelines.Context;
4 | using ModularPipelines.DotNet.Extensions;
5 | using ModularPipelines.DotNet.Options;
6 | using ModularPipelines.Git.Extensions;
7 | using ModularPipelines.Models;
8 | using ModularPipelines.Modules;
9 | using File = ModularPipelines.FileSystem.File;
10 |
11 | namespace AsyncSemaphore.Pipeline.Modules;
12 |
13 | [DependsOn]
14 | [DependsOn]
15 | [DependsOn]
16 | public class PackProjectsModule : Module>
17 | {
18 | protected override async Task?> ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
19 | {
20 | var results = new List();
21 | var packageVersion = await GetModule();
22 | var projectFiles = context.Git().RootDirectory!.GetFiles(f => GetProjectsPredicate(f, context));
23 | foreach (var projectFile in projectFiles)
24 | {
25 | results.Add(await context.DotNet().Pack(new DotNetPackOptions {
26 | ProjectSolution = projectFile.Path,
27 | Configuration = Configuration.Release,
28 | Properties = new KeyValue[]
29 | {
30 | ("PackageVersion", packageVersion.Value)!,
31 | ("Version", packageVersion.Value)!,
32 | },
33 | IncludeSource = true
34 | }, cancellationToken));
35 | }
36 |
37 | return results;
38 | }
39 |
40 | private bool GetProjectsPredicate(File file, IPipelineContext context)
41 | {
42 | var path = file.Path;
43 | if (!path.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
44 | {
45 | return false;
46 | }
47 |
48 | if (path.Contains("Tests", StringComparison.OrdinalIgnoreCase)
49 | || path.Contains("Pipeline", StringComparison.OrdinalIgnoreCase)
50 | || path.Contains("Benchmark", StringComparison.OrdinalIgnoreCase)
51 | || path.Contains("Example", StringComparison.OrdinalIgnoreCase))
52 | {
53 | return false;
54 | }
55 |
56 | context.Logger.LogInformation("Found File: {File}", path);
57 | return true;
58 | }
59 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/PackageFilesRemovalModule.cs:
--------------------------------------------------------------------------------
1 | using ModularPipelines.Context;
2 | using ModularPipelines.Git.Extensions;
3 | using ModularPipelines.Modules;
4 |
5 | namespace AsyncSemaphore.Pipeline.Modules;
6 |
7 | public class PackageFilesRemovalModule : Module
8 | {
9 | protected override async Task?> ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
10 | {
11 | var packageFiles = context.Git().RootDirectory.GetFiles(path => path.Extension is ".nupkg");
12 |
13 | foreach (var packageFile in packageFiles)
14 | {
15 | packageFile.Delete();
16 | }
17 |
18 | return await NothingAsync();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/PackagePathsModule.cs:
--------------------------------------------------------------------------------
1 | using ModularPipelines.Attributes;
2 | using ModularPipelines.Context;
3 | using ModularPipelines.Extensions;
4 | using ModularPipelines.Git.Extensions;
5 | using ModularPipelines.Modules;
6 | using File = ModularPipelines.FileSystem.File;
7 |
8 | namespace AsyncSemaphore.Pipeline.Modules;
9 |
10 | [DependsOn]
11 | public class PackagePathsModule : Module>
12 | {
13 | protected override async Task?> ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
14 | {
15 | await Task.Yield();
16 |
17 | return context.Git().RootDirectory.AssertExists().GetFiles(x => x.Extension == ".nupkg").ToList();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/RunUnitTestsModule.cs:
--------------------------------------------------------------------------------
1 | using ModularPipelines.Context;
2 | using ModularPipelines.DotNet.Extensions;
3 | using ModularPipelines.DotNet.Options;
4 | using ModularPipelines.Git.Extensions;
5 | using ModularPipelines.Models;
6 | using ModularPipelines.Modules;
7 |
8 | namespace AsyncSemaphore.Pipeline.Modules;
9 |
10 | public class RunUnitTestsModule : Module>
11 | {
12 | protected override async Task?> ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
13 | {
14 | var results = new List();
15 |
16 | foreach (var unitTestProjectFile in context
17 | .Git().RootDirectory!
18 | .GetFiles(file => file.Path.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)
19 | && file.Path.Contains("Tests", StringComparison.OrdinalIgnoreCase)))
20 | {
21 | results.Add(await context.DotNet().Test(new DotNetTestOptions
22 | {
23 | ProjectSolutionDirectoryDllExe = unitTestProjectFile
24 | }, cancellationToken));
25 | }
26 |
27 | return results;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Modules/UploadPackagesToNugetModule.cs:
--------------------------------------------------------------------------------
1 | using AsyncSemaphore.Pipeline.Settings;
2 | using EnumerableAsyncProcessor.Extensions;
3 | using Microsoft.Extensions.Logging;
4 | using Microsoft.Extensions.Options;
5 | using ModularPipelines.Attributes;
6 | using ModularPipelines.Context;
7 | using ModularPipelines.DotNet.Extensions;
8 | using ModularPipelines.DotNet.Options;
9 | using ModularPipelines.Git.Extensions;
10 | using ModularPipelines.Models;
11 | using ModularPipelines.Modules;
12 |
13 | namespace AsyncSemaphore.Pipeline.Modules;
14 |
15 | [DependsOn]
16 | [DependsOn]
17 | public class UploadPackagesToNugetModule : Module
18 | {
19 | private readonly IOptions _options;
20 |
21 | public UploadPackagesToNugetModule(IOptions options)
22 | {
23 | _options = options;
24 | }
25 |
26 | protected override async Task OnBeforeExecute(IPipelineContext context)
27 | {
28 | var packagePaths = await GetModule();
29 |
30 | foreach (var packagePath in packagePaths.Value!)
31 | {
32 | context.Logger.LogInformation("Uploading {File}", packagePath);
33 | }
34 |
35 | await base.OnBeforeExecute(context);
36 | }
37 |
38 | protected override async Task ShouldSkip(IPipelineContext context)
39 | {
40 | var gitVersionInfo = await context.Git().Versioning.GetGitVersioningInformation();
41 |
42 | if (gitVersionInfo.BranchName != "main")
43 | {
44 | return true;
45 | }
46 |
47 | var publishPackages =
48 | context.Environment.EnvironmentVariables.GetEnvironmentVariable("PUBLISH_PACKAGES")!;
49 |
50 | if (!bool.TryParse(publishPackages, out var shouldPublishPackages) || !shouldPublishPackages)
51 | {
52 | return true;
53 | }
54 |
55 | return false;
56 | }
57 |
58 | protected override async Task ExecuteAsync(IPipelineContext context, CancellationToken cancellationToken)
59 | {
60 | ArgumentNullException.ThrowIfNull(_options.Value.ApiKey);
61 |
62 | var gitVersionInformation = await context.Git().Versioning.GetGitVersioningInformation();
63 |
64 | if (gitVersionInformation.BranchName != "main")
65 | {
66 | return await NothingAsync();
67 | }
68 |
69 | var packagePaths = await GetModule();
70 |
71 | return await packagePaths.Value!.SelectAsync(async file => await context.DotNet()
72 | .Nuget
73 | .Push(new DotNetNugetPushOptions(file)
74 | {
75 | Source = "https://api.nuget.org/v3/index.json",
76 | ApiKey = _options.Value.ApiKey!
77 | }, cancellationToken), cancellationToken: cancellationToken).ProcessOneAtATime();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Configuration;
2 | using Microsoft.Extensions.DependencyInjection;
3 | using Microsoft.Extensions.Hosting;
4 | using ModularPipelines.Extensions;
5 | using ModularPipelines.Host;
6 | using AsyncSemaphore.Pipeline.Modules;
7 | using AsyncSemaphore.Pipeline.Modules.LocalMachine;
8 | using AsyncSemaphore.Pipeline.Settings;
9 |
10 | await PipelineHostBuilder.Create()
11 | .ConfigureAppConfiguration((_, builder) =>
12 | {
13 | builder.AddJsonFile("appsettings.json")
14 | .AddUserSecrets()
15 | .AddEnvironmentVariables();
16 | })
17 | .ConfigureServices((context, collection) =>
18 | {
19 | collection.Configure(context.Configuration.GetSection("NuGet"));
20 |
21 | if (context.HostingEnvironment.IsDevelopment())
22 | {
23 | collection.AddModule()
24 | .AddModule()
25 | .AddModule();
26 | }
27 | else
28 | {
29 | collection.AddModule();
30 | }
31 | })
32 | .AddModule()
33 | .AddModule()
34 | .AddModule()
35 | .AddModule()
36 | .AddModule()
37 | .ExecutePipelineAsync();
38 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/Settings/NuGetSettings.cs:
--------------------------------------------------------------------------------
1 | namespace AsyncSemaphore.Pipeline.Settings;
2 |
3 | public record NuGetSettings
4 | {
5 | public string? ApiKey { get; init; }
6 | }
7 |
--------------------------------------------------------------------------------
/AsyncSemaphore.Pipeline/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Debug",
5 | "System": "Information",
6 | "Microsoft": "Information"
7 | }
8 | },
9 | "NuGet": {
10 | "ApiKey": "Override from Secret Source"
11 | }
12 | }
--------------------------------------------------------------------------------
/AsyncSemaphore.UnitTests/AsyncSemaphore.UnitTests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net9.0
5 | enable
6 | enable
7 | exe
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/AsyncSemaphore.UnitTests/Tests.cs:
--------------------------------------------------------------------------------
1 | namespace AsyncSemaphore.UnitTests;
2 |
3 | public class Tests
4 | {
5 | [Test]
6 | public async Task Can_Enter_Immediately()
7 | {
8 | var semaphore = new Semaphores.AsyncSemaphore(1);
9 |
10 | var time = await Measure(async () =>
11 | {
12 | using var @lock = await semaphore.WaitAsync();
13 | });
14 |
15 | await Assert.That(time).IsLessThan(TimeSpan.FromMilliseconds(100));
16 | }
17 |
18 | [Test]
19 | [MethodDataSource(nameof(LoopCounts))]
20 | public async Task WaitsForPreviousSemaphore(int loopCount)
21 | {
22 | var semaphore = new Semaphores.AsyncSemaphore(1);
23 |
24 | var time = await Measure(async () =>
25 | {
26 | for (var i = 0; i < loopCount; i++)
27 | {
28 | using var @lock = await semaphore.WaitAsync();
29 | await DoSomething();
30 | }
31 | });
32 |
33 | await Assert.That(time).IsGreaterThan(TimeSpan.FromMilliseconds(500 * (loopCount - 1)));
34 | }
35 |
36 | [Test]
37 | [MethodDataSource(nameof(LoopCounts))]
38 | public async Task WaitsForPreviousSemaphore_Even_When_Exception_Thrown(int loopCount)
39 | {
40 | var semaphore = new Semaphores.AsyncSemaphore(1);
41 |
42 | var time = await Measure(async () =>
43 | {
44 | for (var i = 0; i < loopCount; i++)
45 | {
46 | try
47 | {
48 | using var @lock = await semaphore.WaitAsync();
49 | await DoSomething();
50 | throw new Exception();
51 | }
52 | catch
53 | {
54 | // ignored
55 | }
56 | }
57 | });
58 |
59 | await Assert.That(time).IsGreaterThan(TimeSpan.FromMilliseconds(500 * (loopCount - 1)));
60 | }
61 |
62 | private Task DoSomething()
63 | {
64 | return Task.Delay(500);
65 | }
66 |
67 | public static IEnumerable LoopCounts() => Enumerable.Range(0, 10);
68 |
69 | private async Task Measure(Func func)
70 | {
71 | var start = DateTime.Now;
72 |
73 | await func();
74 |
75 | return DateTime.Now - start;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/AsyncSemaphore.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncSemaphore", "AsyncSemaphore\AsyncSemaphore.csproj", "{3CA4B800-A00B-4A89-94ED-7645BE8B4123}"
4 | EndProject
5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncSemaphore.UnitTests", "AsyncSemaphore.UnitTests\AsyncSemaphore.UnitTests.csproj", "{C1AE07EC-E589-4615-82C3-0F833D1BA57E}"
6 | EndProject
7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncSemaphore.Pipeline", "AsyncSemaphore.Pipeline\AsyncSemaphore.Pipeline.csproj", "{482D3647-8ECE-459B-9B9C-CC10F94D22ED}"
8 | EndProject
9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncSemaphore.Analyzers", "AsyncSemaphore.Analyzers\AsyncSemaphore.Analyzers\AsyncSemaphore.Analyzers.csproj", "{0B9E2544-85BD-4BD8-A6E0-509EF8A1812A}"
10 | EndProject
11 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncSemaphore.Analyzers.Tests", "AsyncSemaphore.Analyzers\AsyncSemaphore.Analyzers.Tests\AsyncSemaphore.Analyzers.Tests.csproj", "{9A4DA842-8896-485A-A6DC-9A56D2A46E89}"
12 | EndProject
13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncSemaphore.Benchmark", "AsyncSemaphore.Benchmark\AsyncSemaphore.Benchmark.csproj", "{F8AC3ADD-4193-431D-853C-510CD061B1E5}"
14 | EndProject
15 | Global
16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
17 | Debug|Any CPU = Debug|Any CPU
18 | Release|Any CPU = Release|Any CPU
19 | EndGlobalSection
20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
21 | {3CA4B800-A00B-4A89-94ED-7645BE8B4123}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22 | {3CA4B800-A00B-4A89-94ED-7645BE8B4123}.Debug|Any CPU.Build.0 = Debug|Any CPU
23 | {3CA4B800-A00B-4A89-94ED-7645BE8B4123}.Release|Any CPU.ActiveCfg = Release|Any CPU
24 | {3CA4B800-A00B-4A89-94ED-7645BE8B4123}.Release|Any CPU.Build.0 = Release|Any CPU
25 | {C1AE07EC-E589-4615-82C3-0F833D1BA57E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {C1AE07EC-E589-4615-82C3-0F833D1BA57E}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {C1AE07EC-E589-4615-82C3-0F833D1BA57E}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {C1AE07EC-E589-4615-82C3-0F833D1BA57E}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {482D3647-8ECE-459B-9B9C-CC10F94D22ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {482D3647-8ECE-459B-9B9C-CC10F94D22ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {482D3647-8ECE-459B-9B9C-CC10F94D22ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {482D3647-8ECE-459B-9B9C-CC10F94D22ED}.Release|Any CPU.Build.0 = Release|Any CPU
33 | {0B9E2544-85BD-4BD8-A6E0-509EF8A1812A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
34 | {0B9E2544-85BD-4BD8-A6E0-509EF8A1812A}.Debug|Any CPU.Build.0 = Debug|Any CPU
35 | {0B9E2544-85BD-4BD8-A6E0-509EF8A1812A}.Release|Any CPU.ActiveCfg = Release|Any CPU
36 | {0B9E2544-85BD-4BD8-A6E0-509EF8A1812A}.Release|Any CPU.Build.0 = Release|Any CPU
37 | {9A4DA842-8896-485A-A6DC-9A56D2A46E89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38 | {9A4DA842-8896-485A-A6DC-9A56D2A46E89}.Debug|Any CPU.Build.0 = Debug|Any CPU
39 | {9A4DA842-8896-485A-A6DC-9A56D2A46E89}.Release|Any CPU.ActiveCfg = Release|Any CPU
40 | {9A4DA842-8896-485A-A6DC-9A56D2A46E89}.Release|Any CPU.Build.0 = Release|Any CPU
41 | {F8AC3ADD-4193-431D-853C-510CD061B1E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {F8AC3ADD-4193-431D-853C-510CD061B1E5}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {F8AC3ADD-4193-431D-853C-510CD061B1E5}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {F8AC3ADD-4193-431D-853C-510CD061B1E5}.Release|Any CPU.Build.0 = Release|Any CPU
45 | EndGlobalSection
46 | EndGlobal
47 |
--------------------------------------------------------------------------------
/AsyncSemaphore/AsyncSemaphore.cs:
--------------------------------------------------------------------------------
1 | #pragma warning disable SEM0001
2 |
3 | namespace Semaphores;
4 |
5 | public sealed class AsyncSemaphore : IAsyncSemaphore
6 | {
7 | private readonly SemaphoreSlim _semaphoreSlim;
8 |
9 | public AsyncSemaphore(int maxCount)
10 | {
11 | _semaphoreSlim = new(maxCount, maxCount);
12 | }
13 |
14 | ///
15 | public async ValueTask WaitAsync()
16 | {
17 | await _semaphoreSlim.WaitAsync();
18 | return new AsyncSemaphoreReleaser(_semaphoreSlim);
19 | }
20 |
21 | ///
22 | public async ValueTask WaitAsync(TimeSpan timeout)
23 | {
24 | await _semaphoreSlim.WaitAsync(timeout);
25 | return new AsyncSemaphoreReleaser(_semaphoreSlim);
26 | }
27 |
28 | ///
29 | public async ValueTask WaitAsync(CancellationToken cancellationToken)
30 | {
31 | await _semaphoreSlim.WaitAsync(cancellationToken);
32 | return new AsyncSemaphoreReleaser(_semaphoreSlim);
33 | }
34 |
35 | ///
36 | public async ValueTask WaitAsync(TimeSpan timeout, CancellationToken cancellationToken)
37 | {
38 | await _semaphoreSlim.WaitAsync(timeout, cancellationToken);
39 | return new AsyncSemaphoreReleaser(_semaphoreSlim);
40 | }
41 |
42 | ///
43 | public int CurrentCount => _semaphoreSlim.CurrentCount;
44 |
45 | ///
46 | public void Dispose()
47 | {
48 | _semaphoreSlim.Dispose();
49 | }
50 | }
--------------------------------------------------------------------------------
/AsyncSemaphore/AsyncSemaphore.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0; net8.0; net9.0
5 | latest
6 | Semaphores
7 | 99
8 |
9 |
10 |
11 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/AsyncSemaphore/AsyncSemaphoreReleaser.cs:
--------------------------------------------------------------------------------
1 | namespace Semaphores;
2 |
3 | public struct AsyncSemaphoreReleaser : IDisposable
4 | {
5 | private SemaphoreSlim? _semaphoreSlim;
6 |
7 | internal AsyncSemaphoreReleaser(SemaphoreSlim semaphoreSlim)
8 | {
9 | _semaphoreSlim = semaphoreSlim;
10 | }
11 |
12 | public void Dispose()
13 | {
14 | Interlocked.Exchange(ref _semaphoreSlim, null)?.Release();
15 | }
16 | }
--------------------------------------------------------------------------------
/AsyncSemaphore/IAsyncSemaphore.cs:
--------------------------------------------------------------------------------
1 | namespace Semaphores;
2 |
3 | public interface IAsyncSemaphore : IDisposable
4 | {
5 | ///
6 | ValueTask WaitAsync();
7 |
8 | ///
9 | ValueTask WaitAsync(TimeSpan timeout);
10 |
11 | ///
12 | ValueTask WaitAsync(CancellationToken cancellationToken);
13 |
14 | ///
15 | ValueTask WaitAsync(TimeSpan timeout, CancellationToken cancellationToken);
16 |
17 | ///
18 | int CurrentCount { get; }
19 | }
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | enable
5 | enable
6 | preview
7 |
8 |
9 |
10 | MIT
11 | README.md
12 | Tom Longhurst
13 | snupkg
14 | true
15 | true
16 |
17 |
18 |
19 | true
20 |
21 |
22 |
23 | false
24 | preview
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Tom Longhurst
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 |
--------------------------------------------------------------------------------
/NuGet.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AsyncSemaphore
2 |
3 | A simple wrapper around a `SemaphoreSlim` featuring:
4 | - Automatic releasing without try/finally blocks by utilising the IDisposable `using` pattern
5 | - Guarantee that release can only be called once per `WaitAsync` call
6 | - Analyzers to help you implement the desired pattern
7 | - An `IAsyncSemaphore` interface for if you need to mock
8 |
9 | ## Install
10 | `dotnet add package AsyncSemaphore`
11 |
12 | ## Usage
13 |
14 | ```csharp
15 | private readonly AsyncSemaphore _asyncSemaphore = new AsyncSemaphore(1);
16 |
17 | public async Task MyMethod()
18 | {
19 | // Just assign the `IDisposable` returned from `WaitAsync` to a variable and use the using statement with it
20 | using var lockHandle = await _asyncSemaphore.WaitAsync();
21 |
22 | // Do whatever you want - Even if we throw exceptions, we'll release the semaphore once we leave this method's scope
23 | await DoSomethingInsideLock();
24 | }
25 | ```
26 |
27 | or scoped:
28 |
29 | ```csharp
30 | private readonly AsyncSemaphore _asyncSemaphore = new AsyncSemaphore(1);
31 |
32 | public async Task MyMethod()
33 | {
34 | // or create your own scope with {} braces - And after you leave that scope, your lock will be released
35 | using (await _asyncSemaphore.WaitAsync())
36 | {
37 | await DoSomethingInsideLock();
38 | }
39 |
40 | await DoSomethingAfterLockReleased();
41 | }
42 | ```
43 |
44 | Benchmarks and allocations can be seen below.
45 |
46 | ```
47 | BenchmarkDotNet v0.13.12, Windows 11 (10.0.22621.3593/22H2/2022Update/SunValley2)
48 | 11th Gen Intel Core i7-1185G7 3.00GHz, 1 CPU, 8 logical and 4 physical cores
49 | .NET SDK 8.0.106
50 | [Host] : .NET 8.0.6 (8.0.624.26715), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
51 | DefaultJob : .NET 8.0.6 (8.0.624.26715), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
52 | ```
53 |
54 |
55 | | Method | Mean | Error | StdDev | Allocated |
56 | |------------------------------------ |---------:|---------:|---------:|----------:|
57 | | Raw_Semaphore_Slim | 38.89 ns | 0.622 ns | 0.519 ns | - |
58 | | AsyncSemaphore_With_Inherited_Scope | 51.36 ns | 0.466 ns | 0.413 ns | - |
59 | | AsyncSemaphore_With_Braced_Scope | 51.04 ns | 0.274 ns | 0.243 ns | - |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "9.0.300",
4 | "rollForward": "latestMinor",
5 | "allowPrerelease": false
6 | }
7 | }
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "packageRules": [
4 | {
5 | "matchPackageNames": ["/ModularPipelines/"],
6 | "groupName": "ModularPipelines"
7 | }
8 | ]
9 | }
10 |
--------------------------------------------------------------------------------