├── .editorconfig ├── .gitattributes ├── .github └── workflows │ ├── dotnet-format.yml │ ├── dotnetcore.yml │ ├── nuget-tag-publish.yml │ └── stryker.yml ├── .gitignore ├── AsyncWorkerCollection.sln ├── AsyncWorkerCollection.sln.DotSettings ├── AsyncWorkerCollection ├── AsyncAutoResetEvent.cs ├── AsyncManualResetEvent.cs ├── AsyncQueue.cs ├── AsyncTaskQueue_ │ ├── AsyncTaskQueue.cs │ ├── AwaitableTask.cs │ └── AwaitableTaskTResult.cs ├── AsyncWorkerCollection.csproj ├── AsyncWorkerCollection.csproj.DotSettings ├── ConcurrentQueueExtension.cs ├── DoubleBuffer_ │ ├── DoubleBuffer.cs │ ├── DoubleBufferLazyInitializeTask.cs │ ├── DoubleBufferTask.cs │ ├── DoubleBufferTask`T.cs │ └── DoubleBuffer`T.cs ├── ExecuteOnceAwaiter.cs ├── IAsyncDisposable.cs ├── LimitedRunningCountTask.cs └── Reentrancy │ ├── KeepLastReentrancyTask.cs │ ├── QueueReentrancyTask.cs │ └── ReentrancyTask.cs ├── Directory.Build.props ├── LICENSE ├── README.md ├── README.zh-cn.md ├── build └── Version.props ├── docs └── Benchmark.md └── test ├── AsyncWorkerCollection.Benchmarks ├── AsyncWorkerCollection.Benchmarks.csproj ├── BatchProducerAndConsumerDoubleBufferReadAndWriteTests.cs ├── DoubleBufferAddTaskTests.cs ├── ProducerAndConsumerAsyncQueueReadAndWriteTests.cs ├── ProducerAndConsumerAsyncQueueWriteTests.cs └── Program.cs └── AsyncWorkerCollection.Tests ├── AsyncAutoResetEventTests.cs ├── AsyncQueueTest.cs ├── AsyncTaskQueueTest.cs ├── AsyncWorkerCollection.Tests.csproj ├── DoubleBufferTaskDoUtilInitializedTest.cs ├── DoubleBufferTaskTest.cs ├── DoubleBufferTest.cs └── Reentrancy └── QueueReentrancyTaskTests.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | end_of_line = crlf 3 | charset = utf-8-bom 4 | indent_size = 4 5 | insert_final_newline = true 6 | tab_width = 4 7 | trim_trailing_whitespace = true 8 | 9 | [*.{xml,csproj,vbproj,props,targets}] 10 | indent_size =2 11 | indent_style = space 12 | tab_width =2 13 | 14 | [*.{cs,vb}] 15 | dotnet_sort_system_directives_first = true 16 | dotnet_style_coalesce_expression = true:suggestion 17 | dotnet_style_collection_initializer = true:suggestion 18 | dotnet_style_explicit_tuple_names = true:suggestion 19 | dotnet_style_null_propagation = true:suggestion 20 | dotnet_style_object_initializer = true:suggestion 21 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent 22 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent 23 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent 24 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent 25 | dotnet_style_predefined_type_for_locals_parameters_members = true:silent 26 | dotnet_style_predefined_type_for_member_access = true:silent 27 | dotnet_style_prefer_auto_properties = true:silent 28 | dotnet_style_prefer_conditional_expression_over_assignment = true 29 | dotnet_style_prefer_conditional_expression_over_return = true 30 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 31 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 32 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent 33 | dotnet_style_qualification_for_event = false:silent 34 | dotnet_style_qualification_for_field = false:silent 35 | dotnet_style_qualification_for_method = false:silent 36 | dotnet_style_qualification_for_property = false:silent 37 | dotnet_style_readonly_field = true:suggestion 38 | dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent 39 | 40 | [*.cs] 41 | csharp_indent_case_contents = true 42 | csharp_indent_labels = flush_left 43 | csharp_indent_switch_labels = true 44 | csharp_new_line_before_catch = true 45 | csharp_new_line_before_else = true 46 | csharp_new_line_before_finally = true 47 | csharp_new_line_before_members_in_anonymous_types = true 48 | csharp_new_line_before_members_in_object_initializers = true 49 | csharp_new_line_before_open_brace = all 50 | csharp_new_line_between_query_expression_clauses = true 51 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion 52 | csharp_prefer_braces = true:silent 53 | csharp_prefer_simple_default_expression = true:suggestion 54 | csharp_preserve_single_line_blocks = true 55 | csharp_preserve_single_line_statements = true 56 | csharp_space_after_cast = true 57 | csharp_space_after_colon_in_inheritance_clause = true 58 | csharp_space_after_keywords_in_control_flow_statements = true 59 | csharp_space_around_binary_operators = before_and_after 60 | csharp_space_before_colon_in_inheritance_clause = true 61 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 62 | csharp_space_between_method_call_name_and_opening_parenthesis = false 63 | csharp_space_between_method_call_parameter_list_parentheses = false 64 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 65 | csharp_space_between_method_declaration_parameter_list_parentheses = false 66 | csharp_space_between_parentheses = false 67 | csharp_style_conditional_delegate_call = true:suggestion 68 | csharp_style_deconstructed_variable_declaration = true:suggestion 69 | csharp_style_expression_bodied_accessors = true:silent 70 | csharp_style_expression_bodied_constructors = false:silent 71 | csharp_style_expression_bodied_indexers = true:silent 72 | csharp_style_expression_bodied_methods = false:silent 73 | csharp_style_expression_bodied_operators = false:silent 74 | csharp_style_expression_bodied_properties = true:silent 75 | csharp_style_inlined_variable_declaration = true:suggestion 76 | csharp_style_pattern_local_over_anonymous_function = true:suggestion 77 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 78 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 79 | csharp_style_throw_expression = true:suggestion 80 | csharp_style_var_elsewhere = true:silent 81 | csharp_style_var_for_built_in_types = true:silent 82 | csharp_style_var_when_type_is_apparent = true:silent 83 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/dotnet-format.yml: -------------------------------------------------------------------------------- 1 | name: Code format check 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | jobs: 8 | dotnet-format: 9 | runs-on: windows-latest 10 | steps: 11 | 12 | - name: Checkout repo 13 | uses: actions/checkout@v2 14 | with: 15 | ref: ${{ github.head_ref }} 16 | 17 | # 代码文件编码规范机器人,详细请看 [dotnet 在 GitHub 的 Action 上部署自动代码编码规范机器人](https://blog.lindexi.com/post/dotnet-%E5%9C%A8-GitHub-%E7%9A%84-Action-%E4%B8%8A%E9%83%A8%E7%BD%B2%E8%87%AA%E5%8A%A8%E4%BB%A3%E7%A0%81%E7%BC%96%E7%A0%81%E8%A7%84%E8%8C%83%E6%9C%BA%E5%99%A8%E4%BA%BA.html) 18 | - name: Install dotnetCampus.EncodingNormalior 19 | run: dotnet tool update -g dotnetCampus.EncodingNormalior 20 | 21 | - name: Fix encoding 22 | run: EncodingNormalior -f . --TryFix true 23 | 24 | # 代码格式化机器人,详细请看 [dotnet 基于 dotnet format 的 GitHub Action 自动代码格式化机器人](https://blog.lindexi.com/post/dotnet-%E5%9F%BA%E4%BA%8E-dotnet-format-%E7%9A%84-GitHub-Action-%E8%87%AA%E5%8A%A8%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%9C%BA%E5%99%A8%E4%BA%BA.html ) 25 | - name: Install dotnet-format 26 | run: dotnet tool install -g dotnet-format 27 | 28 | - name: Run dotnet format 29 | run: dotnet format 30 | 31 | - name: Commit files 32 | # 下面将使用机器人的账号,你可以替换为你自己的账号 33 | run: | 34 | git config --local user.name "github-actions-dotnet-formatter[bot]" 35 | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" 36 | git commit -a -m 'Automated dotnet-format update' 37 | continue-on-error: true 38 | 39 | - name: Create Pull Request 40 | # if: steps.format.outputs.has-changes == 'true' # 如果有格式化,才继续 41 | uses: peter-evans/create-pull-request@v3 42 | with: 43 | title: '[Bot] Automated PR to fix formatting errors' 44 | body: | 45 | Automated PR to fix formatting errors 46 | committer: GitHub 47 | author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 48 | # 以下是给定代码审查者,需要设置仓库有权限的开发者 49 | assignees: lindexi,walterlv 50 | reviewers: lindexi,walterlv 51 | # 对应的上传分支 52 | branch: t/bot/fix-codeformatting -------------------------------------------------------------------------------- /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: windows-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Setup .NET 13 | uses: actions/setup-dotnet@v1 14 | with: 15 | dotnet-version: | 16 | 3.1.x 17 | 5.0.x 18 | 6.0.x 19 | - name: Build with dotnet 20 | run: dotnet build --configuration Release 21 | - name: Test with dotnet 22 | run: dotnet test --configuration Release 23 | 24 | TestOnLinux: 25 | 26 | runs-on: ubuntu-latest 27 | 28 | steps: 29 | - uses: actions/checkout@v1 30 | - name: Setup .NET 31 | uses: actions/setup-dotnet@v1 32 | with: 33 | dotnet-version: | 34 | 3.1.x 35 | 5.0.x 36 | 6.0.x 37 | - name: Build with dotnet 38 | run: dotnet build --configuration Release -f netcoreapp3.1 39 | - name: Test with dotnet 40 | run: dotnet test --configuration Release --no-build -f netcoreapp3.1 41 | - name: Run Infer# 42 | uses: microsoft/infersharpaction@v1.2 43 | with: 44 | binary-path: AsyncWorkerCollection/bin/Release/netcoreapp3.1 45 | 46 | TestOnMac: 47 | 48 | runs-on: macos-latest 49 | 50 | steps: 51 | - uses: actions/checkout@v1 52 | - name: Setup .NET 53 | uses: actions/setup-dotnet@v1 54 | with: 55 | dotnet-version: | 56 | 3.1.x 57 | 5.0.x 58 | 6.0.x 59 | - name: Build with dotnet 60 | run: dotnet build --configuration Release -f netcoreapp3.1 61 | - name: Test with dotnet 62 | run: dotnet test --configuration Release --no-build -f netcoreapp3.1 -------------------------------------------------------------------------------- /.github/workflows/nuget-tag-publish.yml: -------------------------------------------------------------------------------- 1 | name: publish nuget 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: windows-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Setup .NET 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: | 19 | 3.1.x 20 | 5.0.x 21 | 6.0.x 22 | - name: Install dotnet tool 23 | run: dotnet tool install -g dotnetCampus.TagToVersion 24 | 25 | - name: Set tag to version 26 | run: dotnet TagToVersion -t ${{ github.ref }} 27 | 28 | - name: Build with dotnet 29 | run: | 30 | dotnet build --configuration Release 31 | dotnet pack --configuration Release --no-build 32 | 33 | - name: Install Nuget 34 | uses: nuget/setup-nuget@v1 35 | with: 36 | nuget-version: '5.x' 37 | 38 | - name: Add private GitHub registry to NuGet 39 | run: | 40 | nuget sources add -name github -Source https://nuget.pkg.github.com/dotnet-campus/index.json -Username dotnet-campus -Password ${{ secrets.GITHUB_TOKEN }} 41 | 42 | - name: Push generated package to GitHub registry 43 | run: | 44 | nuget push .\bin\Release\*.nupkg -Source github -SkipDuplicate 45 | nuget push .\bin\Release\*.nupkg -Source https://api.nuget.org/v3/index.json -SkipDuplicate -ApiKey ${{ secrets.NugetKey }} -NoSymbols 46 | -------------------------------------------------------------------------------- /.github/workflows/stryker.yml: -------------------------------------------------------------------------------- 1 | name: Stryker 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | Stryker: 10 | runs-on: windows-latest 11 | steps: 12 | - name: Checkout repo 13 | uses: actions/checkout@v2 14 | with: 15 | ref: ${{ github.head_ref }} 16 | 17 | - name: Install Stryker 18 | run: dotnet tool install -g dotnet-stryker 19 | 20 | - name: Test 21 | run: | 22 | cd test\AsyncWorkerCollection.Tests 23 | dotnet stryker -p="AsyncWorkerCollection.csproj" -r "['html', 'progress']" -------------------------------------------------------------------------------- /.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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /AsyncWorkerCollection.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30413.136 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncWorkerCollection", "AsyncWorkerCollection\AsyncWorkerCollection.csproj", "{8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncWorkerCollection.Tests", "test\AsyncWorkerCollection.Tests\AsyncWorkerCollection.Tests.csproj", "{70F29F77-FE49-45FE-9FED-7162897CB7B2}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsyncWorkerCollection.Benchmarks", "test\AsyncWorkerCollection.Benchmarks\AsyncWorkerCollection.Benchmarks.csproj", "{751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C2CBE79A-B5D0-4116-B5D0-53548DCCCD16}" 13 | ProjectSection(SolutionItems) = preProject 14 | .editorconfig = .editorconfig 15 | Directory.Build.props = Directory.Build.props 16 | EndProjectSection 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Debug|x64 = Debug|x64 22 | Debug|x86 = Debug|x86 23 | Release|Any CPU = Release|Any CPU 24 | Release|x64 = Release|x64 25 | Release|x86 = Release|x86 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Debug|x64.ActiveCfg = Debug|Any CPU 31 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Debug|x64.Build.0 = Debug|Any CPU 32 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Debug|x86.ActiveCfg = Debug|Any CPU 33 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Debug|x86.Build.0 = Debug|Any CPU 34 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Release|x64.ActiveCfg = Release|Any CPU 37 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Release|x64.Build.0 = Release|Any CPU 38 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Release|x86.ActiveCfg = Release|Any CPU 39 | {8A479E25-0FE9-4A67-9AED-8B7E0A46C62D}.Release|x86.Build.0 = Release|Any CPU 40 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Debug|x64.ActiveCfg = Debug|Any CPU 43 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Debug|x64.Build.0 = Debug|Any CPU 44 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Debug|x86.ActiveCfg = Debug|Any CPU 45 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Debug|x86.Build.0 = Debug|Any CPU 46 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Release|x64.ActiveCfg = Release|Any CPU 49 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Release|x64.Build.0 = Release|Any CPU 50 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Release|x86.ActiveCfg = Release|Any CPU 51 | {70F29F77-FE49-45FE-9FED-7162897CB7B2}.Release|x86.Build.0 = Release|Any CPU 52 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Debug|x64.ActiveCfg = Debug|Any CPU 55 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Debug|x64.Build.0 = Debug|Any CPU 56 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Debug|x86.ActiveCfg = Debug|Any CPU 57 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Debug|x86.Build.0 = Debug|Any CPU 58 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Release|Any CPU.ActiveCfg = Release|Any CPU 59 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Release|Any CPU.Build.0 = Release|Any CPU 60 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Release|x64.ActiveCfg = Release|Any CPU 61 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Release|x64.Build.0 = Release|Any CPU 62 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Release|x86.ActiveCfg = Release|Any CPU 63 | {751CD521-7831-4C82-A2A0-D4A5FDC8D3F5}.Release|x86.Build.0 = Release|Any CPU 64 | EndGlobalSection 65 | GlobalSection(SolutionProperties) = preSolution 66 | HideSolutionNode = FALSE 67 | EndGlobalSection 68 | GlobalSection(ExtensibilityGlobals) = postSolution 69 | SolutionGuid = {AB058385-F511-4985-B3F0-B5862FB893AA} 70 | EndGlobalSection 71 | EndGlobal 72 | -------------------------------------------------------------------------------- /AsyncWorkerCollection.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncAutoResetEvent.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | namespace dotnetCampus.Threading 7 | { 8 | /// 9 | /// 异步等待的autoresetevent 10 | /// WaitOneAsync方法会返回一个task,通过await方式等待 11 | /// 12 | #if PublicAsInternal 13 | internal 14 | #else 15 | public 16 | #endif 17 | class AsyncAutoResetEvent : IDisposable 18 | { 19 | /// 20 | /// 提供一个信号初始值,确定是否有信号 21 | /// 22 | /// true为有信号,第一个等待可以直接通过 23 | public AsyncAutoResetEvent(bool initialState) 24 | { 25 | _isSignaled = initialState; 26 | } 27 | 28 | /// 29 | /// 析构方法 30 | /// 31 | ~AsyncAutoResetEvent() 32 | { 33 | Dispose(); 34 | } 35 | 36 | private static readonly Task CompletedSourceTask 37 | = Task.FromResult(true); 38 | 39 | /// 40 | /// 异步等待一个信号,需要 await 等待 41 | /// 42 | /// 可以通过返回值是 true 或 false 判断当前是收到信号还是此类被释放 43 | /// 44 | /// 45 | /// 如果是正常解锁,那么返回 true 值。如果是对象调用 释放,那么返回 false 值 46 | /// 47 | public Task WaitOneAsync() 48 | { 49 | lock (_locker) 50 | { 51 | if (_isDisposed) 52 | { 53 | throw new ObjectDisposedException(nameof(AsyncAutoResetEvent)); 54 | } 55 | 56 | if (_isSignaled) 57 | { 58 | // 按照 AutoResetEvent 的设计,在没有任何等待进入时,如果有设置 Set 方法,那么下一次第一个进入的等待将会通过 59 | // 也就是在没有任何等待时,无论调用多少次 Set 方法,在调用之后只有一个等待通过 60 | _isSignaled = false; 61 | return CompletedSourceTask; 62 | } 63 | 64 | var source = new TaskCompletionSource(); 65 | _waitQueue.Enqueue(source); 66 | return source.Task; 67 | } 68 | } 69 | 70 | /// 71 | /// 设置一个信号量,让一个waitone获得信号,每次调用 方法最多只有一个等待通过 72 | /// 73 | public void Set() 74 | { 75 | TaskCompletionSource? releaseSource = null; 76 | bool result; 77 | lock (_locker) 78 | { 79 | if (_waitQueue.Count > 0) 80 | { 81 | releaseSource = _waitQueue.Dequeue(); 82 | } 83 | 84 | if (releaseSource is null) 85 | { 86 | if (!_isSignaled) 87 | { 88 | _isSignaled = true; 89 | } 90 | } 91 | 92 | // 如果这个类被释放了,那么返回 false 值 93 | result = !_isDisposed; 94 | } 95 | 96 | releaseSource?.SetResult(result); 97 | } 98 | 99 | /// 100 | /// 非线程安全 调用时将会释放所有等待 方法 101 | /// 102 | public void Dispose() 103 | { 104 | lock (_locker) 105 | { 106 | _isDisposed = true; 107 | } 108 | 109 | GC.SuppressFinalize(this); 110 | 111 | while (true) 112 | { 113 | lock (_locker) 114 | { 115 | if (_waitQueue.Count == 0) 116 | { 117 | return; 118 | } 119 | } 120 | 121 | // 修复 https://github.com/dotnet-campus/AsyncWorkerCollection/issues/16 122 | Set(); 123 | } 124 | } 125 | 126 | private bool _isDisposed; 127 | 128 | private readonly object _locker = new object(); 129 | 130 | private readonly Queue> _waitQueue = 131 | new Queue>(); 132 | 133 | /// 134 | /// 用于在没有任何等待时让下一次等待通过 135 | /// 136 | private bool _isSignaled; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncManualResetEvent.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace dotnetCampus.Threading 4 | { 5 | /// 6 | /// 异步等待的manualresetevent 7 | /// WaitOneAsync方法会返回一个task,通过await方式等待 8 | /// 9 | #if PublicAsInternal 10 | internal 11 | #else 12 | public 13 | #endif 14 | class AsyncManualResetEvent 15 | { 16 | /// 17 | /// 提供一个信号初始值,确定是否有信号 18 | /// 19 | /// true为有信号,所有等待可以直接通过 20 | public AsyncManualResetEvent(bool initialState) 21 | { 22 | _source = new TaskCompletionSource(); 23 | 24 | if (initialState) 25 | { 26 | _source.SetResult(true); 27 | } 28 | } 29 | 30 | /// 31 | /// 异步等待一个信号,需要await 32 | /// 33 | /// 34 | public Task WaitOneAsync() 35 | { 36 | lock (_locker) 37 | { 38 | return _source.Task; 39 | } 40 | } 41 | 42 | /// 43 | /// 设置一个信号量,所有等待获得信号 44 | /// 45 | public void Set() 46 | { 47 | lock (_locker) 48 | { 49 | _source.SetResult(true); 50 | } 51 | } 52 | 53 | /// 54 | /// 设置一个信号量,所有wait等待 55 | /// 56 | public void Reset() 57 | { 58 | lock (_locker) 59 | { 60 | if (!_source.Task.IsCompleted) 61 | { 62 | return; 63 | } 64 | 65 | _source = new TaskCompletionSource(); 66 | } 67 | } 68 | 69 | private readonly object _locker = new object(); 70 | 71 | private TaskCompletionSource _source; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncQueue.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | #if !NETCOREAPP 9 | using ValueTask = System.Threading.Tasks.Task; 10 | #endif 11 | 12 | namespace dotnetCampus.Threading 13 | { 14 | /// 15 | /// 提供一个异步的队列。可以使用 await 关键字异步等待出队,当有元素入队的时候,等待就会完成。 16 | /// 17 | /// 存入异步队列中的元素类型。 18 | #if PublicAsInternal 19 | internal 20 | #else 21 | public 22 | #endif 23 | class AsyncQueue : IDisposable, IAsyncDisposable 24 | { 25 | private readonly SemaphoreSlim _semaphoreSlim; 26 | private readonly ConcurrentQueue _queue; 27 | 28 | /// 29 | /// 创建一个 的新实例。 30 | /// 31 | public AsyncQueue() 32 | { 33 | _semaphoreSlim = new SemaphoreSlim(0); 34 | _queue = new ConcurrentQueue(); 35 | } 36 | 37 | /// 38 | /// 获取此刻队列中剩余元素的个数。 39 | /// 请注意:因为线程安全问题,此值获取后值即过时,所以获取此值的代码需要自行处理线程安全。 40 | /// 41 | public int Count => _queue.Count; 42 | 43 | /// 44 | /// 入队。 45 | /// 46 | /// 要入队的元素。 47 | public void Enqueue(T item) 48 | { 49 | ThrowIfDisposing(); 50 | _queue.Enqueue(item); 51 | _semaphoreSlim.Release(); 52 | } 53 | 54 | /// 55 | /// 将一组元素全部入队。 56 | /// 57 | /// 要入队的元素序列。 58 | public void EnqueueRange(IEnumerable source) 59 | { 60 | ThrowIfDisposing(); 61 | var n = 0; 62 | foreach (var item in source) 63 | { 64 | _queue.Enqueue(item); 65 | n++; 66 | } 67 | 68 | _semaphoreSlim.Release(n); 69 | } 70 | 71 | /// 72 | /// 异步等待出队。当队列中有新的元素时,异步等待就会返回。 73 | /// 74 | /// 75 | /// 你可以通过此 来取消等待出队。 76 | /// 由于此方法有返回值,后续方法可能依赖于此返回值,所以如果取消将抛出 。 77 | /// 78 | /// 可以异步等待的队列返回的元素。 79 | public async Task DequeueAsync(CancellationToken cancellationToken = default) 80 | { 81 | Interlocked.Increment(ref _dequeueAsyncEnterCount); 82 | try 83 | { 84 | while (!_isDisposed) 85 | { 86 | await _semaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false); 87 | 88 | if (_queue.TryDequeue(out var item)) 89 | { 90 | return item; 91 | } 92 | else 93 | { 94 | // 当前没有任务 95 | lock (_queue) 96 | { 97 | // 事件不是线程安全,因为存在事件的加等 98 | CurrentFinished?.Invoke(this, EventArgs.Empty); 99 | } 100 | } 101 | } 102 | 103 | return default!; 104 | } 105 | finally 106 | { 107 | Interlocked.Decrement(ref _dequeueAsyncEnterCount); 108 | } 109 | } 110 | 111 | /// 112 | /// 当前进入 还没被释放的次数 113 | /// 114 | private int _dequeueAsyncEnterCount; 115 | 116 | /// 117 | /// 等待当前的所有任务执行完成 118 | /// 119 | /// 120 | public async ValueTask WaitForCurrentFinished() 121 | { 122 | if (_queue.Count == 0) 123 | { 124 | return; 125 | } 126 | 127 | using var currentFinishedTask = new CurrentFinishedTask(this); 128 | 129 | // 有线程执行事件触发,刚好此时在创建 CurrentFinishedTask 对象 130 | // 此时需要重新判断是否存在任务 131 | if (_queue.Count == 0) 132 | { 133 | return; 134 | } 135 | 136 | await currentFinishedTask.WaitForCurrentFinished().ConfigureAwait(false); 137 | } 138 | 139 | /// 140 | /// 主要用来释放锁,让 DequeueAsync 方法返回,解决因为锁让此对象内存不释放 141 | /// 142 | /// 这个方法不是线程安全 143 | /// 144 | public void Dispose() 145 | { 146 | ThrowIfDisposing(); 147 | _isDisposing = true; 148 | 149 | // 当释放的时候,将通过 _queue 的 Clear 清空内容,而通过 _semaphoreSlim 的释放让 DequeueAsync 释放锁 150 | // 此时将会在 DequeueAsync 进入 TryDequeue 方法,也许此时依然有开发者在 _queue.Clear() 之后插入元素,但是没关系,我只是需要保证调用 Dispose 之后会让 DequeueAsync 方法返回而已 151 | _isDisposed = true; 152 | _queue.Clear(); 153 | if (_dequeueAsyncEnterCount > 0) 154 | { 155 | // 释放 DequeueAsync 方法,释放次数为 DequeueAsync 在调用的次数 156 | _semaphoreSlim.Release(_dequeueAsyncEnterCount); 157 | } 158 | _semaphoreSlim.Dispose(); 159 | } 160 | 161 | /// 162 | /// 等待任务执行完成之后返回,此方法不是线程安全 163 | /// 164 | /// 如果在调用此方法同时添加任务,那么添加的任务存在线程安全 165 | /// 166 | /// 167 | public async ValueTask DisposeAsync() 168 | { 169 | ThrowIfDisposing(); 170 | _isDisposing = true; 171 | await WaitForCurrentFinished().ConfigureAwait(false); 172 | 173 | // 在设置 _isDisposing 完成,刚好有 Enqueue 的代码 174 | if (_queue.Count != 0) 175 | { 176 | // 再次等待 177 | await WaitForCurrentFinished().ConfigureAwait(false); 178 | } 179 | 180 | // 其实此时依然可以存在有线程在 Enqueue 执行,但是此时就忽略了 181 | 182 | // 设置变量,此时循环将会跳出 183 | _isDisposed = true; 184 | _semaphoreSlim.Release(int.MaxValue); 185 | _semaphoreSlim.Dispose(); 186 | } 187 | 188 | // 这里忽略线程安全 189 | private void ThrowIfDisposing() 190 | { 191 | if (_isDisposing) 192 | { 193 | throw new ObjectDisposedException(nameof(AsyncQueue)); 194 | } 195 | } 196 | 197 | private event EventHandler? CurrentFinished; 198 | 199 | private bool _isDisposing; 200 | private bool _isDisposed; 201 | 202 | class CurrentFinishedTask : IDisposable 203 | { 204 | public CurrentFinishedTask(AsyncQueue asyncQueue) 205 | { 206 | _asyncQueue = asyncQueue; 207 | 208 | lock (_asyncQueue) 209 | { 210 | _asyncQueue.CurrentFinished += CurrentFinished; 211 | } 212 | } 213 | 214 | private void CurrentFinished(object? sender, EventArgs e) 215 | { 216 | _currentFinishedTaskCompletionSource.TrySetResult(true); 217 | } 218 | 219 | public async ValueTask WaitForCurrentFinished() 220 | { 221 | await _currentFinishedTaskCompletionSource.Task.ConfigureAwait(false); 222 | } 223 | 224 | private readonly TaskCompletionSource _currentFinishedTaskCompletionSource = 225 | new TaskCompletionSource(); 226 | 227 | private readonly AsyncQueue _asyncQueue; 228 | 229 | public void Dispose() 230 | { 231 | lock (_asyncQueue) 232 | { 233 | _currentFinishedTaskCompletionSource.TrySetResult(true); 234 | _asyncQueue.CurrentFinished -= CurrentFinished; 235 | } 236 | } 237 | } 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncTaskQueue_/AsyncTaskQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Diagnostics; 4 | using System.Threading.Tasks; 5 | 6 | namespace dotnetCampus.Threading 7 | { 8 | /// 9 | /// 异步任务队列,将任务加入到队列里面按照顺序执行 10 | /// 11 | #if PublicAsInternal 12 | internal 13 | #else 14 | public 15 | #endif 16 | class AsyncTaskQueue : IDisposable 17 | { 18 | /// 19 | /// 异步任务队列 20 | /// 21 | public AsyncTaskQueue() 22 | { 23 | _autoResetEvent = new AsyncAutoResetEvent(false); 24 | _ = InternalRunning(); 25 | } 26 | 27 | #region 执行 28 | 29 | /// 30 | /// 执行异步操作 31 | /// 32 | /// 返回结果类型 33 | /// 异步操作 34 | /// IsInvalid:异步操作是否有效(多任务时,如果设置了,只会保留最后一个任务有效);Result:异步操作结果 35 | public async Task<(bool IsInvalid, T Result)> ExecuteAsync(Func> func) 36 | { 37 | var task = GetExecutableTask(func); 38 | var result = await await task; 39 | if (!task.IsValid) 40 | { 41 | result = default; 42 | } 43 | 44 | return (task.IsValid, result); 45 | } 46 | 47 | /// 48 | /// 执行异步操作 49 | /// 50 | /// 51 | /// 52 | /// 53 | // ReSharper disable once UnusedTypeParameter 54 | public async Task ExecuteAsync(Func func) 55 | { 56 | var task = GetExecutableTask(func); 57 | await await task; 58 | return task.IsValid; 59 | } 60 | 61 | #endregion 62 | 63 | #region 添加任务 64 | 65 | /// 66 | /// 获取待执行任务 67 | /// 68 | /// 69 | /// 70 | private AwaitableTask GetExecutableTask(Action action) 71 | { 72 | var awaitableTask = new AwaitableTask(new Task(action)); 73 | AddPendingTaskToQueue(awaitableTask); 74 | return awaitableTask; 75 | } 76 | 77 | /// 78 | /// 获取待执行任务 79 | /// 80 | /// 81 | /// 82 | /// 83 | private AwaitableTask GetExecutableTask(Func function) 84 | { 85 | var awaitableTask = new AwaitableTask(new Task(function)); 86 | AddPendingTaskToQueue(awaitableTask); 87 | return awaitableTask; 88 | } 89 | 90 | /// 91 | /// 添加待执行任务到队列 92 | /// 93 | /// 94 | /// 95 | private void AddPendingTaskToQueue(AwaitableTask task) 96 | { 97 | //添加队列,加锁。 98 | lock (Locker) 99 | { 100 | if (_isDisposing || _isDisposed) 101 | { 102 | task.SetNotExecutable(); 103 | return; 104 | } 105 | 106 | _queue.Enqueue(task); 107 | //开始执行任务 108 | _autoResetEvent.Set(); 109 | } 110 | } 111 | 112 | #endregion 113 | 114 | #region 内部运行 115 | 116 | private async Task InternalRunning() 117 | { 118 | while (!_isDisposing) 119 | { 120 | Task waitOneTask = null; 121 | bool shouldWaitOneTask = _queue.Count == 0; 122 | 123 | lock (Locker) 124 | { 125 | if (_isDisposing || _isDisposed) 126 | { 127 | // 理论上判断 _isDisposed 为 true 时,此时 _isDisposing 一定为 true 的值 128 | // 但是如果是在 _autoResetEvent 被释放时,由此线程进入到此判断里面 129 | // 那么 _isDisposing 为 true 但 _isDisposed 为 false 的值 130 | // 原因在于 _isDisposed 等待 _autoResetEvent 释放之后,再设置为 true 的值 131 | // 同时因为进入的线程是在释放 _autoResetEvent 的线程,因此 lock (Locker) 无效 132 | return; 133 | } 134 | 135 | // 在锁里获取异步锁,这样可以解决在释放的时候,调用异步锁已被释放 136 | if (shouldWaitOneTask) 137 | { 138 | waitOneTask = _autoResetEvent.WaitOneAsync(); 139 | } 140 | } 141 | 142 | if (shouldWaitOneTask) 143 | { 144 | //等待后续任务 145 | var result = await waitOneTask.ConfigureAwait(false); 146 | 147 | if (result is false) 148 | { 149 | // 啥时候是 false 的值?在 _autoResetEvent 被释放的时候 150 | // 此时将会因为其他线程调用 _autoResetEvent 的 Dispose 方法而继续往下走 151 | // 此时在 Dispose 方法里面是获得了 Locker 这个对象的锁。也就是说此时如果判断 _isDisposed 属性,是一定是 false 的值。原因是 _isDisposed 的设置是在 Locker 锁里面,同时也在 _autoResetEvent 被释放之后。尽管有在外层的 while (!_isDisposing) 进行一次判断,然而此获取非线程安全。因此需要进行三步判断才能是安全的 152 | // 第一步是最外层的 while (!_isDisposing) 进行判断。第二步是进入 Locker 锁时,同时判断 _isDisposing 和 _isDisposed 对象(其实判断 _isDisposing 即可)不过多余的判断没有什么锅 153 | // 第三步是此分支,如果当前释放了,那就应该返回了 154 | return; 155 | } 156 | } 157 | 158 | while (TryGetNextTask(out var task)) 159 | { 160 | //如已从队列中删除 161 | if (!task.Executable) continue; 162 | //添加是否已释放的判断 163 | if (!_isDisposing) 164 | { 165 | if (UseSingleThread) 166 | { 167 | task.RunSynchronously(); 168 | } 169 | else 170 | { 171 | task.Start(); 172 | } 173 | } 174 | } 175 | } 176 | } 177 | 178 | /// 179 | /// 上一次异步操作 180 | /// 181 | private AwaitableTask _lastDoingTask; 182 | 183 | private bool TryGetNextTask(out AwaitableTask task) 184 | { 185 | task = null; 186 | while (_queue.Count > 0) 187 | { 188 | //获取并从队列中移除任务 189 | if (_queue.TryDequeue(out task) && (!AutoCancelPreviousTask || _queue.Count == 0)) 190 | { 191 | //设置进行中的异步操作无效 192 | _lastDoingTask?.MarkTaskInvalid(); 193 | _lastDoingTask = task; 194 | return true; 195 | } 196 | 197 | Debug.Assert(task != null); 198 | //并发操作,设置任务不可执行 199 | task.SetNotExecutable(); 200 | } 201 | 202 | return false; 203 | } 204 | 205 | #endregion 206 | 207 | #region dispose 208 | 209 | /// 210 | public void Dispose() 211 | { 212 | Dispose(true); 213 | GC.SuppressFinalize(this); 214 | } 215 | 216 | /// 217 | /// 析构任务队列 218 | /// 219 | ~AsyncTaskQueue() 220 | { 221 | Dispose(false); 222 | } 223 | 224 | private void Dispose(bool disposing) 225 | { 226 | if (_isDisposed) return; 227 | 228 | lock (Locker) 229 | { 230 | if (_isDisposed) return; 231 | _isDisposing = true; 232 | if (disposing) 233 | { 234 | } 235 | 236 | // 先调用 Clear 方法,然后调用 _autoResetEvent.Dispose 此时的任务如果还没执行的,就不会执行 237 | _queue.Clear(); 238 | _autoResetEvent.Dispose(); 239 | _isDisposed = true; 240 | } 241 | } 242 | 243 | #endregion 244 | 245 | #region 属性及字段 246 | 247 | /// 248 | /// 是否使用单线程完成任务 249 | /// 250 | public bool UseSingleThread { get; set; } = true; 251 | 252 | /// 253 | /// 自动取消以前的任务,此属性应该是在创建对象完成之后给定,不允许在任务执行过程中更改 254 | /// 255 | /// 设置和获取不需要加上锁,因为这是原子的,业务上也不会有开发者不断修改这个值。也就是说这个属性只有在对象创建就给定 256 | public bool AutoCancelPreviousTask 257 | { 258 | get => _autoCancelPreviousTask; 259 | set 260 | { 261 | if (_lastDoingTask != null) 262 | { 263 | // 仅用于开发时告诉开发者,在任务开始之后调用是不对的 264 | throw new InvalidOperationException($"此属性应该是在创建对象完成之后给定,不允许在任务执行过程中更改"); 265 | } 266 | 267 | _autoCancelPreviousTask = value; 268 | } 269 | } 270 | 271 | private object Locker => _queue; 272 | private bool _isDisposed; 273 | private bool _isDisposing; 274 | private readonly ConcurrentQueue _queue = new ConcurrentQueue(); 275 | private readonly AsyncAutoResetEvent _autoResetEvent; 276 | // ReSharper disable once RedundantDefaultMemberInitializer 277 | private bool _autoCancelPreviousTask = false; 278 | 279 | #endregion 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncTaskQueue_/AwaitableTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.CompilerServices; 3 | using System.Threading.Tasks; 4 | 5 | namespace dotnetCampus.Threading 6 | { 7 | /// 8 | /// 可等待的任务 9 | /// 10 | #if PublicAsInternal 11 | internal 12 | #else 13 | public 14 | #endif 15 | class AwaitableTask 16 | { 17 | /// 18 | /// 获取任务是否为不可执行状态 19 | /// 20 | public bool Executable { get; private set; } = true; 21 | 22 | /// 23 | /// 获取任务是否有效 24 | /// 注:对无效任务,可以不做处理。减少并发操作导致的干扰 25 | /// 26 | public bool IsValid { get; private set; } = true; 27 | 28 | /// 29 | /// 设置任务不可执行 30 | /// 31 | public void SetNotExecutable() 32 | { 33 | Executable = false; 34 | } 35 | 36 | /// 37 | /// 标记任务无效 38 | /// 39 | public void MarkTaskInvalid() 40 | { 41 | IsValid = false; 42 | } 43 | 44 | #region Task 45 | 46 | private readonly Task _task; 47 | 48 | /// 49 | /// 初始化可等待的任务。 50 | /// 51 | /// 52 | public AwaitableTask(Task task) 53 | { 54 | _task = task ?? throw new ArgumentNullException(nameof(task)); 55 | } 56 | 57 | /// 58 | /// 获取任务是否已完成 59 | /// 60 | public bool IsCompleted => _task.IsCompleted; 61 | 62 | /// 63 | /// 任务的Id 64 | /// 65 | public int TaskId => _task.Id; 66 | 67 | /// 68 | /// 开始任务 69 | /// 70 | public void Start() 71 | { 72 | _task.Start(); 73 | } 74 | 75 | /// 76 | /// 同步执行开始任务 77 | /// 78 | public void RunSynchronously() 79 | { 80 | _task.RunSynchronously(); 81 | } 82 | 83 | #endregion 84 | 85 | #region TaskAwaiter 86 | 87 | /// 88 | /// 获取任务等待器 89 | /// 90 | /// 91 | public TaskAwaiter GetAwaiter() 92 | { 93 | return new TaskAwaiter(this); 94 | } 95 | 96 | /// Provides an object that waits for the completion of an asynchronous task. 97 | //[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true, Synchronization = true)] 98 | public struct TaskAwaiter : INotifyCompletion 99 | { 100 | private readonly AwaitableTask _awaitableTask; 101 | 102 | /// 103 | /// 任务等待器 104 | /// 105 | /// 106 | public TaskAwaiter(AwaitableTask awaitableTask) 107 | { 108 | _awaitableTask = awaitableTask; 109 | } 110 | 111 | /// 112 | /// 任务是否完成. 113 | /// 114 | public bool IsCompleted => _awaitableTask._task.IsCompleted; 115 | 116 | /// 117 | public void OnCompleted(Action continuation) 118 | { 119 | var This = this; 120 | _awaitableTask._task.ContinueWith(t => 121 | { 122 | if (This._awaitableTask.Executable) continuation?.Invoke(); 123 | }); 124 | } 125 | 126 | /// 127 | /// 获取任务结果 128 | /// 129 | public void GetResult() 130 | { 131 | _awaitableTask._task.Wait(); 132 | } 133 | } 134 | 135 | #endregion 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncTaskQueue_/AwaitableTaskTResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.CompilerServices; 3 | using System.Threading.Tasks; 4 | 5 | namespace dotnetCampus.Threading 6 | { 7 | /// 8 | /// 可等待的任务 9 | /// 10 | /// 11 | #if PublicAsInternal 12 | internal 13 | #else 14 | public 15 | #endif 16 | class AwaitableTask : AwaitableTask 17 | { 18 | /// 19 | /// 初始化可等待的任务 20 | /// 21 | /// 需要执行的任务 22 | public AwaitableTask(Task task) : base(task) 23 | { 24 | _task = task; 25 | } 26 | 27 | private readonly Task _task; 28 | 29 | #region TaskAwaiter 30 | 31 | /// 32 | /// 获取任务等待器 33 | /// 34 | /// 35 | public new TaskAwaiter GetAwaiter() 36 | { 37 | return new TaskAwaiter(this); 38 | } 39 | 40 | /// 41 | /// 任务等待器 42 | /// 43 | //[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true, Synchronization = true)] 44 | public new struct TaskAwaiter : INotifyCompletion 45 | { 46 | private readonly AwaitableTask _awaitableTask; 47 | 48 | /// 49 | /// 初始化任务等待器 50 | /// 51 | /// 52 | public TaskAwaiter(AwaitableTask awaitableTask) 53 | { 54 | _awaitableTask = awaitableTask; 55 | } 56 | 57 | /// 58 | /// 任务是否已完成。 59 | /// 60 | public bool IsCompleted => _awaitableTask._task.IsCompleted; 61 | 62 | /// 63 | public void OnCompleted(Action continuation) 64 | { 65 | var This = this; 66 | _awaitableTask._task.ContinueWith(t => 67 | { 68 | if (This._awaitableTask.Executable) continuation?.Invoke(); 69 | }); 70 | } 71 | 72 | /// 73 | /// 获取任务结果。 74 | /// 75 | /// 76 | public TResult GetResult() 77 | { 78 | return _awaitableTask._task.Result; 79 | } 80 | } 81 | 82 | #endregion 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncWorkerCollection.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net45;netcoreapp3.1;netstandard2.0 5 | dotnetCampus.Threading 6 | true 7 | true 8 | dotnetCampus.AsyncWorkerCollection 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/AsyncWorkerCollection.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True -------------------------------------------------------------------------------- /AsyncWorkerCollection/ConcurrentQueueExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace dotnetCampus.Threading 9 | { 10 | static class ConcurrentQueueExtension 11 | { 12 | // 在 .NET Framework 4.5 没有清理方法 13 | public static void Clear(this ConcurrentQueue queue) 14 | { 15 | while (queue.TryDequeue(out _)) 16 | { 17 | 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/DoubleBuffer_/DoubleBuffer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace dotnetCampus.Threading 6 | { 7 | /// 8 | /// 提供双缓存 线程安全列表 9 | /// 10 | /// 用于存放 的集合 11 | /// 12 | /// 写入的时候写入到一个列表,通过 SwitchBuffer 方法,可以切换当前缓存 13 | #if PublicAsInternal 14 | internal 15 | #else 16 | public 17 | #endif 18 | class DoubleBuffer where T : class, ICollection 19 | { 20 | /// 21 | /// 创建双缓存 22 | /// 23 | /// 24 | /// 25 | public DoubleBuffer(T aList, T bList) 26 | { 27 | AList = aList; 28 | BList = bList; 29 | 30 | CurrentList = AList; 31 | } 32 | 33 | /// 34 | /// 加入元素到缓存 35 | /// 36 | /// 37 | public void Add(TU t) 38 | { 39 | lock (_lock) 40 | { 41 | CurrentList.Add(t); 42 | } 43 | } 44 | 45 | /// 46 | /// 切换缓存 47 | /// 48 | /// 49 | public T SwitchBuffer() 50 | { 51 | lock (_lock) 52 | { 53 | if (ReferenceEquals(CurrentList, AList)) 54 | { 55 | CurrentList = BList; 56 | return AList; 57 | } 58 | else 59 | { 60 | CurrentList = AList; 61 | return BList; 62 | } 63 | } 64 | } 65 | 66 | /// 67 | /// 执行完所有任务 68 | /// 69 | /// 当前缓存里面存在的任务,请不要保存传入的 List 参数 70 | public void DoAll(Action action) 71 | { 72 | while (true) 73 | { 74 | var buffer = SwitchBuffer(); 75 | if (buffer.Count == 0) break; 76 | 77 | action(buffer); 78 | buffer.Clear(); 79 | } 80 | } 81 | 82 | /// 83 | /// 执行完所有任务 84 | /// 85 | /// 当前缓存里面存在的任务,请不要保存传入的 List 参数 86 | /// 87 | public async Task DoAllAsync(Func action) 88 | { 89 | while (true) 90 | { 91 | var buffer = SwitchBuffer(); 92 | if (buffer.Count == 0) break; 93 | 94 | await action(buffer).ConfigureAwait(false); 95 | buffer.Clear(); 96 | } 97 | } 98 | 99 | /// 100 | /// 获取当前是否为空,线程不安全,必须自行加锁 101 | /// 102 | /// 103 | internal bool GetIsEmpty() 104 | { 105 | return AList.Count == 0 && BList.Count == 0; 106 | } 107 | 108 | /// 109 | /// 用于给其他类型的同步使用的对象 110 | /// 111 | internal object SyncObject => _lock; 112 | private readonly object _lock = new object(); 113 | 114 | private T CurrentList { set; get; } 115 | 116 | private T AList { get; } 117 | private T BList { get; } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/DoubleBuffer_/DoubleBufferLazyInitializeTask.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Threading.Tasks; 6 | 7 | #pragma warning disable 164 8 | 9 | namespace dotnetCampus.Threading 10 | { 11 | /// 12 | /// 可等待初始化之后才执行实际任务的双缓存工具 13 | /// 14 | /// 在完成初始化之后需要调用 方法 15 | /// 16 | /// 17 | /// 18 | #if PublicAsInternal 19 | internal 20 | #else 21 | public 22 | #endif 23 | class DoubleBufferLazyInitializeTask 24 | { 25 | /// 26 | /// 初始化可等待初始化之后才执行实际任务的双缓存工具 27 | /// 28 | /// 只有在 方法被调用之后,才会执行的实际任务 29 | public DoubleBufferLazyInitializeTask(Func, Task> runTask) 30 | { 31 | _runTask = runTask; 32 | _doubleBufferTask = new DoubleBufferTask(DoInner); 33 | } 34 | 35 | /// 36 | /// 初始化完成之后调用,这个方法只能调用一次 37 | /// 38 | /// 如果调用多次,那么将抛出此异常 39 | public void OnInitialized() 40 | { 41 | if (_isInitialized) 42 | { 43 | throw new InvalidOperationException($"禁止多次设置初始化完成"); 44 | } 45 | 46 | // 这个变量设置无视线程安全,处理线程安全在 _waitForInitializationTask 字段 47 | _isInitialized = true; 48 | 49 | lock (Locker) 50 | { 51 | if (_waitForInitializationTask != null) 52 | { 53 | // 如果不是空 54 | // 那么设置任务完成 55 | _waitForInitializationTask.SetResult(true); 56 | } 57 | else 58 | { 59 | // 如果是空,那么 DoInner 还没进入,此时啥都不需要做 60 | } 61 | } 62 | } 63 | 64 | /// 65 | /// 加入任务 66 | /// 67 | /// 68 | public void AddTask(T data) 69 | { 70 | _doubleBufferTask.AddTask(data); 71 | } 72 | 73 | /// 74 | /// 完成任务 75 | /// 76 | public void Finish() => _doubleBufferTask.Finish(); 77 | 78 | /// 79 | /// 等待完成任务,只有在调用 之后,所有任务执行完成才能完成 80 | /// 81 | /// 82 | public Task WaitAllTaskFinish() => _doubleBufferTask.WaitAllTaskFinish(); 83 | 84 | private object Locker => _doubleBufferTask; 85 | 86 | private readonly Func, Task> _runTask; 87 | private readonly DoubleBufferTask _doubleBufferTask; 88 | 89 | private bool _isInitialized; 90 | private TaskCompletionSource? _waitForInitializationTask; 91 | 92 | private async Task DoInner(List dataList) 93 | { 94 | // 根据 DoubleBufferTask 的设计,这个方法只有一个线程进入 95 | FirstCheckInitialized: // 标签:第一个判断初始化方法 96 | if (!_isInitialized) 97 | { 98 | // 还没有初始化,等待一下 99 | // 如果此时还没有任务可以等待,那么创建一下任务 100 | lock (Locker) 101 | { 102 | SecondCheckInitialized: // 标签:第二个判断初始化方法 103 | if (!_isInitialized) 104 | { 105 | // 此时的值一定是空 106 | Debug.Assert(_waitForInitializationTask == null); 107 | _waitForInitializationTask = new TaskCompletionSource(); 108 | } 109 | } 110 | 111 | if (!_isInitialized) 112 | { 113 | await _waitForInitializationTask!.Task.ConfigureAwait(false); 114 | } 115 | else 116 | { 117 | // 此时初始化方法被调用,因此不需要再调用等待 118 | // 如果先进入 FirstCheckInitialized 标签的第一个判断初始化方法,此时 OnInitialized 没有被调用 119 | // 因此进入分支 120 | // 如果刚好此时 OnInitialized 方法进入,同时设置了 _isInitialized 是 true 值 121 | // 如果此时的 OnInitialized 方法比 DoInner 先获得锁,那么将判断 _waitForInitializationTask 是空,啥都不做 122 | // 然后 DoInner 在等待 OnInitialized 的 Locker 锁,进入锁之后,先通过 SecondCheckInitialized 标签的第二个判断初始化方法 123 | // 这个判断是线程安全的,因此如果是 OnInitialized 已进入同时获取锁,那么此时在等待 Locker 锁之后一定拿到新的值 124 | // 如果是 DoInner 先获得锁,那么此时也许 _isInitialized 不靠谱,但其实不依赖 _isInitialized 靠谱,因此 _isInitialized 只有一个状态,就是从 false 到 true 的值 125 | // 此时如果判断 _isInitialized 是 true 的值,也就不需要再创建一个任务用来等待了 126 | // 也就会最终进入此分支 127 | } 128 | 129 | // 只需要等待一次,然后可以释放内存 130 | _waitForInitializationTask = null; 131 | } 132 | 133 | await _runTask(dataList).ConfigureAwait(false); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/DoubleBuffer_/DoubleBufferTask.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | #if !NETCOREAPP 8 | using ValueTask = System.Threading.Tasks.Task; 9 | #endif 10 | 11 | namespace dotnetCampus.Threading 12 | { 13 | /// 14 | /// 双缓存任务 15 | /// 16 | #if PublicAsInternal 17 | internal 18 | #else 19 | public 20 | #endif 21 | class DoubleBufferTask : IAsyncDisposable 22 | where T : class, ICollection 23 | { 24 | /// 25 | /// 创建双缓存任务,执行任务的方法放在 方法 26 | /// 27 | /// 28 | /// 执行任务的方法 29 | /// 30 | /// 传入的 List<T> 就是需要执行的任务,请不要将传入的 List<T> 保存到本地字段 31 | /// 32 | /// 此委托需要自行完全处理异常,否则将会抛到后台线程 33 | /// 34 | /// 35 | /// 36 | /// 37 | public DoubleBufferTask(T aList, T bList, Func doTask) 38 | { 39 | _doTask = doTask; 40 | DoubleBuffer = new DoubleBuffer(aList, bList); 41 | } 42 | 43 | /// 44 | /// 加入任务 45 | /// 46 | /// 47 | public void AddTask(TU t) 48 | { 49 | var isSetFinish = _isSetFinish; 50 | if (isSetFinish == 1) 51 | { 52 | // 被设置完成了,业务上就不应该再次给任何的数据内容 53 | throw new InvalidOperationException($"The DoubleBufferTask has been set finish."); 54 | } 55 | 56 | DoubleBuffer.Add(t); 57 | _ = DoInner(); 58 | } 59 | 60 | private async Task DoInner() 61 | { 62 | // ReSharper disable once InconsistentlySynchronizedField 63 | if (_isDoing) return; 64 | 65 | lock (Locker) 66 | { 67 | if (_isDoing) return; 68 | _isDoing = true; 69 | } 70 | 71 | while (true) 72 | { 73 | await DoubleBuffer.DoAllAsync(_doTask).ConfigureAwait(false); 74 | 75 | lock (Locker) 76 | { 77 | if (DoubleBuffer.GetIsEmpty()) 78 | { 79 | _isDoing = false; 80 | Finished?.Invoke(this, EventArgs.Empty); 81 | break; 82 | } 83 | } 84 | } 85 | } 86 | 87 | /// 88 | /// 完成任务 89 | /// 90 | public void Finish() 91 | { 92 | var isSetFinish = Interlocked.CompareExchange(ref _isSetFinish, 1, 0); 93 | if (isSetFinish == 1) 94 | { 95 | // 多次设置完成任务 96 | // 重复多次调用 Finish 方法,第二次调用将无效 97 | return; 98 | } 99 | 100 | lock (Locker) 101 | { 102 | if (!_isDoing) 103 | { 104 | FinishTask.SetResult(true); 105 | return; 106 | } 107 | 108 | Finished += OnFinished; 109 | } 110 | } 111 | 112 | private void OnFinished(object? sender, EventArgs args) 113 | { 114 | Finished -= OnFinished; 115 | FinishTask.SetResult(true); 116 | } 117 | 118 | /// 119 | /// 等待完成任务,只有在调用 之后,所有任务执行完成才能完成 120 | /// 121 | /// 122 | public Task WaitAllTaskFinish() 123 | { 124 | return FinishTask.Task; 125 | } 126 | 127 | private TaskCompletionSource FinishTask { get; } = new TaskCompletionSource(); 128 | 129 | /// 130 | /// 是否调用了 方法,因为此方法不适合多次重复调用 131 | /// 132 | /// 选用 int 的考虑是为了做原子无锁设计,提升性能 133 | private int _isSetFinish; 134 | 135 | private volatile bool _isDoing; 136 | 137 | private event EventHandler? Finished; 138 | 139 | private readonly Func _doTask; 140 | 141 | private DoubleBuffer DoubleBuffer { get; } 142 | private object Locker => DoubleBuffer.SyncObject; 143 | 144 | /// 145 | public async ValueTask DisposeAsync() 146 | { 147 | Finish(); 148 | await WaitAllTaskFinish().ConfigureAwait(false); 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/DoubleBuffer_/DoubleBufferTask`T.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | namespace dotnetCampus.Threading 7 | { 8 | /// 9 | /// 双缓存任务 10 | /// 11 | /// 12 | #if PublicAsInternal 13 | internal 14 | #else 15 | public 16 | #endif 17 | class DoubleBufferTask : DoubleBufferTask, T> 18 | { 19 | /// 20 | /// 创建双缓存任务,执行任务的方法放在 方法 21 | /// 22 | /// 23 | public DoubleBufferTask(Func, Task> doTask) : base(new List(), new List(), doTask) 24 | { 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/DoubleBuffer_/DoubleBuffer`T.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace dotnetCampus.Threading 4 | { 5 | /// 6 | /// 提供双缓存 线程安全列表 7 | /// 8 | /// 写入的时候写入到一个列表,通过 SwitchBuffer 方法,可以切换当前缓存 9 | #if PublicAsInternal 10 | internal 11 | #else 12 | public 13 | #endif 14 | class DoubleBuffer : DoubleBuffer, T> 15 | { 16 | /// 17 | /// 创建使用 的双缓存 18 | /// 19 | public DoubleBuffer() : base(new List(), new List()) 20 | { 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/ExecuteOnceAwaiter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace dotnetCampus.Threading 6 | { 7 | /// 8 | /// 只执行一次的等待 9 | /// 10 | /// 11 | #if PublicAsInternal 12 | internal 13 | #else 14 | public 15 | #endif 16 | class ExecuteOnceAwaiter 17 | { 18 | /// 19 | /// 创建只执行一次的等待,调用 时,无论调用多少次,只会执行 一次 20 | /// 21 | /// 因为此类使用了锁,因此需要调用方处理 自身线程安全问题 22 | /// 23 | /// 执行的具体逻辑,需要调用方处理自身线程安全问题 24 | public ExecuteOnceAwaiter(Func> asyncAction) 25 | { 26 | _asyncAction = asyncAction; 27 | } 28 | 29 | /// 30 | /// 执行传入的具体逻辑,无论多少线程多少次调用,传入的具体逻辑只会执行一次 31 | /// 32 | /// 33 | public Task ExecuteAsync() 34 | { 35 | lock (_locker) 36 | { 37 | if (_executionResult != null) 38 | { 39 | return _executionResult; 40 | } 41 | 42 | _executionResult = _asyncAction(); 43 | return _executionResult; 44 | } 45 | } 46 | 47 | /// 48 | /// 在传入的具体逻辑执行完成之后,设置允许重新执行。如果此具体逻辑还在执行中,那么此方法调用无效 49 | /// 50 | public void ResetWhileCompleted() 51 | { 52 | lock (_locker) 53 | { 54 | if (_executionResult?.IsCompleted is true) 55 | { 56 | _executionResult = null; 57 | } 58 | } 59 | } 60 | 61 | private readonly object _locker = new object(); 62 | 63 | private readonly Func> _asyncAction; 64 | private Task _executionResult; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/IAsyncDisposable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | #if !NETCOREAPP 8 | using ValueTask = System.Threading.Tasks.Task; 9 | #endif 10 | 11 | namespace dotnetCampus.Threading 12 | { 13 | // 尽管设置 csproj 不引用这个文件,但是在源代码引用的时候,依然会添加这个文件,因此需要判断当前如果是 net45 就忽略这个代码 14 | #if NETFRAMEWORK || NETSTANDARD2_0 15 | // 这个接口在 .NET Framework 4.5 没有 16 | interface IAsyncDisposable 17 | { 18 | ValueTask DisposeAsync(); 19 | } 20 | #endif 21 | } 22 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/LimitedRunningCountTask.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | #if !NETCOREAPP 7 | using ValueTask = System.Threading.Tasks.Task; 8 | #endif 9 | 10 | namespace dotnetCampus.Threading 11 | { 12 | /// 13 | /// 限制执行数量的任务,执行的任务超过设置的数量将可以等待直到正在执行任务数小于设置的数量 14 | /// 15 | #if PublicAsInternal 16 | internal 17 | #else 18 | public 19 | #endif 20 | class LimitedRunningCountTask 21 | { 22 | /// 23 | /// 创建限制执行数量的任务 24 | /// 25 | /// 允许最大的执行数量的任务 26 | public LimitedRunningCountTask(uint maxRunningCount) 27 | { 28 | MaxRunningCount = maxRunningCount; 29 | } 30 | 31 | /// 32 | /// 执行的任务数 33 | /// 34 | public int RunningCount 35 | { 36 | set 37 | { 38 | lock (Locker) 39 | { 40 | _runningCount = value; 41 | } 42 | } 43 | get 44 | { 45 | lock (Locker) 46 | { 47 | return _runningCount; 48 | } 49 | } 50 | } 51 | 52 | /// 53 | /// 允许最大的执行数量的任务 54 | /// 55 | public uint MaxRunningCount { get; } 56 | 57 | /// 58 | /// 加入执行任务 59 | /// 60 | /// 61 | public void Add(Task task) 62 | { 63 | RunningCount++; 64 | lock (Locker) 65 | { 66 | Buffer.Add(task); 67 | 68 | RunningBreakTask?.TrySetResult(true); 69 | } 70 | 71 | _ = RunningInner(); 72 | } 73 | 74 | /// 75 | /// 加入等待任务,在空闲之后等待才会返回 76 | /// 77 | /// 78 | /// 79 | public async ValueTask AddAsync(Task task) 80 | { 81 | // ReSharper disable once MethodHasAsyncOverload 82 | Add(task); 83 | await WaitForFree().ConfigureAwait(false); 84 | } 85 | 86 | /// 87 | /// 等待空闲 88 | /// 89 | /// 90 | public async ValueTask WaitForFree() 91 | { 92 | if (WaitForFreeTask == null) 93 | { 94 | return; 95 | } 96 | 97 | await WaitForFreeTask.Task.ConfigureAwait(false); 98 | } 99 | 100 | private TaskCompletionSource? RunningBreakTask 101 | { 102 | set 103 | { 104 | lock (Locker) 105 | { 106 | _runningBreakTask = value; 107 | } 108 | } 109 | get 110 | { 111 | lock (Locker) 112 | { 113 | return _runningBreakTask; 114 | } 115 | } 116 | } 117 | 118 | private TaskCompletionSource? WaitForFreeTask 119 | { 120 | set 121 | { 122 | lock (Locker) 123 | { 124 | _waitForFreeTask = value; 125 | } 126 | } 127 | get 128 | { 129 | lock (Locker) 130 | { 131 | return _waitForFreeTask; 132 | } 133 | } 134 | } 135 | 136 | private List Buffer { get; } = new List(); 137 | 138 | private object Locker => Buffer; 139 | 140 | private bool _isRunning; 141 | 142 | private int _runningCount; 143 | 144 | private TaskCompletionSource? _runningBreakTask; 145 | 146 | private TaskCompletionSource? _waitForFreeTask; 147 | 148 | private async Task RunningInner() 149 | { 150 | // ReSharper disable once InconsistentlySynchronizedField 151 | if (_isRunning) 152 | { 153 | return; 154 | } 155 | 156 | lock (Locker) 157 | { 158 | if (_isRunning) 159 | { 160 | return; 161 | } 162 | 163 | _isRunning = true; 164 | } 165 | 166 | List runningTaskList; 167 | lock (Locker) 168 | { 169 | runningTaskList = Buffer.ToList(); 170 | Buffer.Clear(); 171 | RunningBreakTask = new TaskCompletionSource(); 172 | runningTaskList.Add(RunningBreakTask.Task); 173 | 174 | SetWaitForFreeTask(); 175 | } 176 | 177 | while (runningTaskList.Count > 0) 178 | { 179 | // 加入等待 180 | await Task.WhenAny(runningTaskList).ConfigureAwait(false); 181 | 182 | // 干掉不需要的任务 183 | runningTaskList.RemoveAll(task => task.IsCompleted); 184 | 185 | lock (Locker) 186 | { 187 | runningTaskList.AddRange(Buffer); 188 | Buffer.Clear(); 189 | 190 | RunningCount = runningTaskList.Count; 191 | 192 | if (!RunningBreakTask.Task.IsCompleted) 193 | { 194 | runningTaskList.Add(RunningBreakTask.Task); 195 | } 196 | else 197 | { 198 | RunningBreakTask = new TaskCompletionSource(); 199 | runningTaskList.Add(RunningBreakTask.Task); 200 | } 201 | 202 | if (runningTaskList.Count < MaxRunningCount) 203 | { 204 | WaitForFreeTask?.TrySetResult(true); 205 | } 206 | else 207 | { 208 | SetWaitForFreeTask(); 209 | } 210 | } 211 | } 212 | 213 | lock (Locker) 214 | { 215 | _isRunning = false; 216 | } 217 | 218 | void SetWaitForFreeTask() 219 | { 220 | if (runningTaskList.Count > MaxRunningCount) 221 | { 222 | if (WaitForFreeTask?.Task.IsCompleted is false) 223 | { 224 | } 225 | else 226 | { 227 | WaitForFreeTask = new TaskCompletionSource(); 228 | } 229 | } 230 | } 231 | } 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/Reentrancy/KeepLastReentrancyTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace dotnetCampus.Threading.Reentrancy 8 | { 9 | /// 10 | /// 执行当前队列中的最后一个任务,并对所有当前队列任务赋值该任务结果。 11 | /// 12 | /// 13 | /// 重入任务中单次执行时所使用的参数。 14 | /// 此重入策略不会忽略任何参数。 15 | /// 16 | /// 17 | /// 重入任务中单次执行时所得到的返回值。 18 | /// 此重入策略不会忽略任何返回值。 19 | /// 20 | #if PublicAsInternal 21 | internal 22 | #else 23 | public 24 | #endif 25 | sealed class KeepLastReentrancyTask : ReentrancyTask 26 | { 27 | /// 28 | /// 用于原子操作判断当前是否正在执行队列中的可重入任务。 29 | /// 1 表示当前正在执行可重入任务;0 表示不确定。 30 | /// 不可使用 bool 类型,因为 bool 类型无法执行可靠的原子操作。 31 | /// 32 | private volatile int _isRunning; 33 | 34 | /// 35 | /// 由于原子操作仅提供高性能的并发处理而不保证准确性,因此需要一个锁来同步 中值为 0 时所指的不确定情况。 36 | /// 不能使用一个锁来同步所有情况是因为在锁中使用 async/await 是不安全的,因此避免在锁中执行异步任务;我们使用原子操作来判断异步任务的执行条件。 37 | /// 38 | private readonly object _locker = new object(); 39 | 40 | /// 41 | /// 使用一个并发队列来表示目前已加入到队列中的全部可重入任务。 42 | /// 因为我们的 不能锁全部队列操作(原因见 ),因此需要使用并发队列。 43 | /// 44 | private readonly ConcurrentQueue _queue = new ConcurrentQueue(); 45 | 46 | /// 47 | /// 使用一个队列表示当前执行任务开始时所有需要进行赋值结果的任务。 48 | /// 49 | private readonly Queue _skipQueue = new Queue(); 50 | 51 | private readonly bool _configureAwait; 52 | 53 | /// 54 | /// 创建以KeepLast策略执行的可重入任务。 55 | /// 56 | /// 可重入任务本身。 57 | public KeepLastReentrancyTask(Func> task) : base(task) { } 58 | 59 | /// 60 | /// 创建以KeepLast策略执行的可重入任务。 61 | /// 62 | /// 可重入任务本身。 63 | /// 64 | public KeepLastReentrancyTask(Func> task, bool configureAwait) : this(task) 65 | { 66 | _configureAwait = configureAwait; 67 | } 68 | 69 | /// 70 | /// 以KeepLast策略执行重入任务,并获取此次重入任务的返回值。 71 | /// 此重入策略会确保执行当前队列中的最后一个任务,并对所有当前队列任务赋值该任务结果。 72 | /// 73 | /// 此次重入任务使用的参数。 74 | /// 重入任务本次执行的返回值。 75 | public override Task InvokeAsync(TParameter arg) 76 | { 77 | var wrapper = new TaskWrapper(() => RunCore(arg), _configureAwait); 78 | _queue.Enqueue(wrapper); 79 | _ = Run(); 80 | return wrapper.AsTask(); 81 | } 82 | 83 | /// 84 | /// 以KeepLast策略执行重入任务。此方法确保线程安全。 85 | /// 86 | private async Task Run() 87 | { 88 | var isRunning = Interlocked.CompareExchange(ref _isRunning, 1, 0); 89 | if (isRunning is 1) 90 | { 91 | lock (_locker) 92 | { 93 | if (_isRunning is 1) 94 | { 95 | // 当前已经在执行队列,因此无需继续执行。 96 | return; 97 | } 98 | } 99 | } 100 | 101 | //下面这段是在临界区执行的,不存在多线程问题 102 | var hasTask = true; 103 | while (hasTask) 104 | { 105 | TaskWrapper runTask = null; 106 | // 当前还没有任何队列开始执行,因此需要开始执行队列。 107 | while (_queue.TryDequeue(out var wrapper)) 108 | { 109 | //所有任务项转入执行队列 110 | if (runTask != null) 111 | { 112 | _skipQueue.Enqueue(runTask); 113 | } 114 | 115 | runTask = wrapper; 116 | } 117 | 118 | if (runTask != null) 119 | { 120 | // 内部已包含异常处理,因此外面可以无需捕获或者清理。 121 | await runTask.RunAsync().ConfigureAwait(_configureAwait); 122 | //完成后对等待队列中的项赋值 123 | if (runTask.Exception != null) 124 | { 125 | SetException(runTask.Exception); 126 | } 127 | else 128 | { 129 | SetResult(runTask.Result); 130 | } 131 | } 132 | 133 | lock (_locker) 134 | { 135 | hasTask = _queue.TryPeek(out _); 136 | if (!hasTask) 137 | { 138 | //退出临界区 139 | _isRunning = 0; 140 | } 141 | } 142 | } 143 | } 144 | 145 | private void SetException(Exception exception) 146 | { 147 | while (_skipQueue.Count > 0) 148 | { 149 | var taskWrapper = _skipQueue.Dequeue(); 150 | taskWrapper.SetException(exception); 151 | } 152 | } 153 | 154 | private void SetResult(TReturn result) 155 | { 156 | while (_skipQueue.Count > 0) 157 | { 158 | var taskWrapper = _skipQueue.Dequeue(); 159 | taskWrapper.SetResult(result); 160 | } 161 | } 162 | 163 | /// 164 | /// 包装一个异步任务,以便在可以执行此异步任务的情况下可以在其他方法中监视其完成情况。 165 | /// 166 | private class TaskWrapper 167 | { 168 | /// 169 | /// 创建一个任务包装。 170 | /// 171 | internal TaskWrapper(Func> workingTask, bool configureAwait) 172 | { 173 | _taskSource = new TaskCompletionSource(); 174 | _task = workingTask; 175 | _configureAwait = configureAwait; 176 | } 177 | 178 | private readonly TaskCompletionSource _taskSource; 179 | private readonly Func> _task; 180 | private readonly bool _configureAwait; 181 | 182 | public TReturn Result { get; set; } 183 | public Exception Exception { get; set; } 184 | 185 | /// 186 | /// 执行此异步任务。 187 | /// 188 | internal async Task RunAsync() 189 | { 190 | try 191 | { 192 | var task = _task(); 193 | if (task is null) 194 | { 195 | throw new InvalidOperationException("在指定 KeepLastReentrancyTask 的任务时,方法内不允许返回 null。请至少返回 Task.FromResult(null)。"); 196 | } 197 | var result = await task.ConfigureAwait(_configureAwait); 198 | _taskSource.SetResult(result); 199 | Result = result; 200 | } 201 | #pragma warning disable CA1031 // 异常已经被通知到异步代码中,因此此处无需处理异常。 202 | catch (Exception ex) 203 | { 204 | _taskSource.SetException(ex); 205 | Exception = ex; 206 | } 207 | #pragma warning restore CA1031 // 异常已经被通知到异步代码中,因此此处无需处理异常。 208 | } 209 | 210 | public void SetResult(TReturn result) 211 | { 212 | if (_taskSource.Task.IsCompleted || _taskSource.Task.IsFaulted) 213 | { 214 | return; 215 | } 216 | 217 | _taskSource.SetResult(result); 218 | } 219 | 220 | public void SetException(Exception exception) 221 | { 222 | if (_taskSource.Task.IsCompleted || _taskSource.Task.IsFaulted) 223 | { 224 | return; 225 | } 226 | 227 | _taskSource.SetException(exception); 228 | } 229 | 230 | /// 231 | /// 将此异步包装器作为 使用,以便获得 async/await 特性。 232 | /// 233 | internal Task AsTask() => _taskSource.Task; 234 | } 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/Reentrancy/QueueReentrancyTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | namespace dotnetCampus.Threading.Reentrancy 7 | { 8 | /// 9 | /// 以队列策略执行的可重入任务。 10 | /// 11 | /// 12 | /// 重入任务中单次执行时所使用的参数。 13 | /// 此重入策略不会忽略任何参数。 14 | /// 15 | /// 16 | /// 重入任务中单次执行时所得到的返回值。 17 | /// 此重入策略不会忽略任何返回值。 18 | /// 19 | #if PublicAsInternal 20 | internal 21 | #else 22 | public 23 | #endif 24 | sealed class QueueReentrancyTask : ReentrancyTask 25 | { 26 | /// 27 | /// 用于原子操作判断当前是否正在执行队列中的可重入任务。 28 | /// 1 表示当前正在执行可重入任务;0 表示不确定。 29 | /// 不可使用 bool 类型,因为 bool 类型无法执行可靠的原子操作。 30 | /// 31 | private volatile int _isRunning; 32 | 33 | /// 34 | /// 由于原子操作仅提供高性能的并发处理而不保证准确性,因此需要一个锁来同步 中值为 0 时所指的不确定情况。 35 | /// 不能使用一个锁来同步所有情况是因为在锁中使用 async/await 是不安全的,因此避免在锁中执行异步任务;我们使用原子操作来判断异步任务的执行条件。 36 | /// 37 | private readonly object _locker = new object(); 38 | 39 | /// 40 | /// 使用一个并发队列来表示目前已加入到队列中的全部可重入任务。 41 | /// 因为我们的 不能锁全部队列操作(原因见 ),因此需要使用并发队列。 42 | /// 43 | private readonly ConcurrentQueue _queue = new ConcurrentQueue(); 44 | 45 | private readonly bool _configureAwait; 46 | 47 | /// 48 | /// 创建以队列策略执行的可重入任务。 49 | /// 50 | /// 可重入任务本身。 51 | /// 52 | public QueueReentrancyTask(Func> task, bool configureAwait) : base(task) 53 | { 54 | _configureAwait = configureAwait; 55 | } 56 | 57 | /// 58 | /// 创建以队列策略执行的可重入任务 59 | /// 60 | /// 61 | public QueueReentrancyTask(Func> task) : this(task, false) { } 62 | 63 | /// 64 | /// 以队列策略执行重入任务,并获取此次重入任务的返回值。 65 | /// 此重入策略会确保执行每一次可重入任务。 66 | /// 67 | /// 此次重入任务使用的参数。 68 | /// 重入任务本次执行的返回值。 69 | public override Task InvokeAsync(TParameter arg) 70 | { 71 | var wrapper = new TaskWrapper(() => RunCore(arg)); 72 | _queue.Enqueue(wrapper); 73 | _ = Run(); 74 | return wrapper.AsTask(); 75 | } 76 | 77 | /// 78 | /// 以队列策略执行重入任务。此方法确保线程安全。 79 | /// 80 | private async Task Run() 81 | { 82 | var isRunning = Interlocked.CompareExchange(ref _isRunning, 1, 0); 83 | if (isRunning is 1) 84 | { 85 | lock (_locker) 86 | { 87 | if (_isRunning is 1) 88 | { 89 | // 当前已经在执行队列,因此无需继续执行。 90 | return; 91 | } 92 | } 93 | } 94 | 95 | var hasTask = true; 96 | while (hasTask) 97 | { 98 | // 当前还没有任何队列开始执行,因此需要开始执行队列。 99 | while (_queue.TryDequeue(out var wrapper)) 100 | { 101 | // 内部已包含异常处理,因此外面可以无需捕获或者清理。 102 | await wrapper.RunAsync().ConfigureAwait(_configureAwait); 103 | } 104 | 105 | lock (_locker) 106 | { 107 | hasTask = _queue.TryPeek(out _); 108 | if (!hasTask) 109 | { 110 | _isRunning = 0; 111 | } 112 | } 113 | } 114 | } 115 | 116 | /// 117 | /// 包装一个异步任务,以便在可以执行此异步任务的情况下可以在其他方法中监视其完成情况。 118 | /// 119 | private class TaskWrapper 120 | { 121 | /// 122 | /// 创建一个任务包装。 123 | /// 124 | internal TaskWrapper(Func> workingTask) 125 | { 126 | _taskSource = new TaskCompletionSource(); 127 | _task = workingTask; 128 | } 129 | 130 | private readonly TaskCompletionSource _taskSource; 131 | private readonly Func> _task; 132 | 133 | /// 134 | /// 执行此异步任务。 135 | /// 136 | internal async Task RunAsync() 137 | { 138 | try 139 | { 140 | var result = await _task().ConfigureAwait(false); 141 | _taskSource.SetResult(result); 142 | } 143 | #pragma warning disable CA1031 // 异常已经被通知到异步代码中,因此此处无需处理异常。 144 | catch (Exception ex) 145 | { 146 | _taskSource.SetException(ex); 147 | } 148 | #pragma warning restore CA1031 // 异常已经被通知到异步代码中,因此此处无需处理异常。 149 | } 150 | 151 | /// 152 | /// 将此异步包装器作为 使用,以便获得 async/await 特性。 153 | /// 154 | internal Task AsTask() => _taskSource.Task; 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /AsyncWorkerCollection/Reentrancy/ReentrancyTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace dotnetCampus.Threading.Reentrancy 5 | { 6 | /// 7 | /// 表示一个可重入任务。使用不同的可重入任务子类,你可以使用不同的重入策略处理并发任务的重入问题。 8 | /// 9 | /// 10 | /// 重入任务中单次执行时所使用的参数。 11 | /// 注意,对于部分类型的重入任务,参数可能会被选择性忽略;具体取决于不同的重入策略是否会导致任务是否全部被执行。 12 | /// 13 | /// 14 | /// 重入任务中单次执行时所得到的返回值。 15 | /// 注意,对于部分类型的重入任务,返回值可能会是此类型的默认值;具体取决于不同的重入策略是否会导致任务是否全部被执行。 16 | /// 17 | #if PublicAsInternal 18 | internal 19 | #else 20 | public 21 | #endif 22 | abstract class ReentrancyTask 23 | { 24 | /// 25 | /// 在派生类中执行重入任务的时候,从此处获取需要执行的可重入异步任务。 26 | /// 27 | protected Func> WorkingTask { get; } 28 | 29 | /// 30 | /// 初始化可重入任务的公共基类。 31 | /// 32 | /// 可重入任务本身。 33 | protected ReentrancyTask(Func> task) 34 | { 35 | WorkingTask = task ?? throw new ArgumentNullException(nameof(task)); 36 | } 37 | 38 | /// 39 | /// 执行重入任务,并获取此次重入任务的返回值。 40 | /// 如果此次任务不被执行,那么将返回类型的默认值。 41 | /// 42 | /// 此次重入任务使用的参数。 43 | /// 重入任务当次执行的返回值。 44 | public abstract Task InvokeAsync(TParameter arg); 45 | 46 | /// 47 | /// 执行实际的异步任务,也就是用户部分的代码。 48 | /// 49 | /// 此次重入任务使用的参数。 50 | /// 此次执行的返回值。 51 | protected Task RunCore(TParameter arg) => WorkingTask(arg); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | $(MSBuildThisFileDirectory)bin\$(Configuration) 5 | dotnet-campus 6 | dotnet-campus 7 | latest 8 | false 9 | 一个支持异步方法和支持高性能多线程的工具集合。A collection of tools that support asynchronous methods and support high-performance multithreading. 10 | Copyright (c) 2020-2023 dotnet-campus 11 | https://github.com/dotnet-campus/AsyncWorkerCollection 12 | https://github.com/dotnet-campus/AsyncWorkerCollection.git 13 | git 14 | MIT 15 | dotnet;yaml; 16 | 17 | 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020-2023 dotnet campus 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dotnetCampus.AsyncWorkerCollection 2 | 3 | [中文](README.zh-cn.md) 4 | 5 | | Build | NuGet | 6 | | -- | -- | 7 | |![](https://github.com/dotnet-campus/AsyncWorkerCollection/workflows/.NET%20Core/badge.svg)|[![](https://img.shields.io/nuget/v/dotnetCampus.AsyncWorkerCollection.svg)](https://www.nuget.org/packages/dotnetCampus.AsyncWorkerCollection)| 8 | 9 | A collection of tools that support asynchronous methods and support high-performance multithreading. 10 | 11 | ## Install NuGet package 12 | 13 | Two different libraries are provided for installation. 14 | 15 | ### Install the traditionary NuGet Dll library 16 | 17 | .NET CLI: 18 | 19 | ``` 20 | dotnet add package dotnetCampus.AsyncWorkerCollection 21 | ``` 22 | 23 | PackageReference: 24 | 25 | ```xml 26 | 27 | ``` 28 | 29 | ### Install the [SourceYard](https://github.com/dotnet-campus/SourceYard) NuGet source code 30 | 31 | .NET CLI: 32 | 33 | ``` 34 | dotnet add package dotnetCampus.AsyncWorkerCollection.Source --version 1.2.1 35 | ``` 36 | 37 | PackageReference: 38 | 39 | ```xml 40 | 41 | all 42 | runtime; build; native; contentfiles; analyzers 43 | 44 | ``` 45 | 46 | ## Usage 47 | 48 | ### AsyncQueue 49 | 50 | An asynchronous queue that supports multiple threads 51 | 52 | Create a queue: 53 | 54 | ```csharp 55 | var asyncQueue = new AsyncQueue(); 56 | ``` 57 | 58 | Add task to queue: 59 | 60 | ```csharp 61 | asyncQueue.Enqueue(new FooTask()); 62 | ``` 63 | 64 | Waiting for the task to dequeue: 65 | 66 | ```csharp 67 | var fooTask = await asyncQueue.DequeueAsync(); 68 | ``` 69 | 70 | The advantage of AsyncQueue over Channel is that it supports .NET Framework 45 and simple 71 | 72 | ### DoubleBufferTask 73 | 74 | DoubleBufferTask supports multi-threaded fast input data and single-threaded batch processing of data, and supports waiting for buffer execution to complete 75 | 76 | ```csharp 77 | var doubleBufferTask = new DoubleBufferTask(list => 78 | { 79 | // Method to perform batch List tasks 80 | // The incoming delegate will be called when there is data in the DoubleBufferTask, and it means that there is at least one element in the list 81 | }); 82 | 83 | // Multiple other threads call this code to add the task data 84 | doubleBufferTask.AddTask(new Foo()); 85 | 86 | // After the business code is completed, call the Finish method to indicate that no more tasks are added 87 | // This Finish method is not thread-safe 88 | doubleBufferTask.Finish(); 89 | 90 | // Other threads can call WaitAllTaskFinish to wait for the completion of all task data in DoubleBufferTask 91 | // It will return after be Finish method be called and the all the task data be handled 92 | await doubleBufferTask.WaitAllTaskFinish(); 93 | ``` 94 | 95 | ### AsyncAutoResetEvent 96 | 97 | Asynchronous version of AutoResetEvent lock 98 | 99 | AsyncAutoResetEvent is functionally the same as AutoResetEvent, except that WaitOne is replaced with WaitOneAsync to support asynchronous waiting 100 | 101 | ### AsyncManualResetEvent 102 | 103 | Asynchronous version of ManualResetEvent lock 104 | 105 | AsyncManualResetEvent is functionally the same as ManualResetEvent, except that WaitOne is replaced with WaitOneAsync to support asynchronous waiting 106 | 107 | ## Benchmark 108 | 109 | See [Benchmark.md](docs/Benchmark.md) 110 | 111 | ## Contributing 112 | 113 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/dotnet-campus/AsyncWorkerCollection/pulls) 114 | 115 | If you would like to contribute, feel free to create a [Pull Request](https://github.com/dotnet-campus/AsyncWorkerCollection/pulls), or give us [Bug Report](https://github.com/dotnet-campus/AsyncWorkerCollection/issues/new). -------------------------------------------------------------------------------- /README.zh-cn.md: -------------------------------------------------------------------------------- 1 | # dotnetCampus.AsyncWorkerCollection 2 | 3 | 一个支持异步方法和支持高性能多线程的工具集合 4 | 5 | 6 | ## 安装 NuGet 包 7 | 8 | 这个库提供了两个不同的包可以给大家安装。其中一个包是传统的 Dll 引用包。另一个包是使用 [SourceYard](https://github.com/dotnet-campus/SourceYard) 打出来的源代码包,源代码包安装之后将会引用源代码 9 | 10 | ### 安装传统 NuGet Dll 库 11 | 12 | .NET CLI: 13 | 14 | ``` 15 | dotnet add package dotnetCampus.AsyncWorkerCollection 16 | ``` 17 | 18 | PackageReference: 19 | 20 | ```xml 21 | 22 | ``` 23 | 24 | ### 安装源代码包 25 | 26 | .NET CLI: 27 | 28 | ``` 29 | dotnet add package dotnetCampus.AsyncWorkerCollection.Source --version 1.2.1 30 | ``` 31 | 32 | PackageReference: 33 | 34 | ```xml 35 | 36 | all 37 | runtime; build; native; contentfiles; analyzers 38 | 39 | ``` 40 | 41 | 安装源代码包将会让你的项目引用的是 dotnetCampus.AsyncWorkerCollection 的 C# 源代码,而不是 dll 程序集。使用此方法可以减少 dll 文件以及程序集的引入 42 | 43 | ## 使用方法 44 | 45 | ### AsyncQueue 46 | 47 | 高性能内存生产者消费者队列,支持多线程入队和多线程等待出队 48 | 49 | 最简使用方法 50 | 51 | ```csharp 52 | // 下面的 FooTask 是任意自定义类 53 | var asyncQueue = new AsyncQueue(); 54 | 55 | // 线程1 56 | asyncQueue.Enqueue(new FooTask()); 57 | 58 | // 线程2 59 | var fooTask = await asyncQueue.DequeueAsync(); 60 | ``` 61 | 62 | 详细请看 [dotnet 使用 AsyncQueue 创建高性能内存生产者消费者队列](https://blog.lindexi.com/post/dotnet-%E4%BD%BF%E7%94%A8-AsyncQueue-%E5%88%9B%E5%BB%BA%E9%AB%98%E6%80%A7%E8%83%BD%E5%86%85%E5%AD%98%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85%E9%98%9F%E5%88%97.html ) 63 | 64 | ### DoubleBufferTask 65 | 66 | 双缓存任务和双缓存类,支持多线程快速写入和单线程读取批量的数据,支持等待缓存执行完成 67 | 68 | 最简使用方法 69 | 70 | ```csharp 71 | var doubleBufferTask = new DoubleBufferTask(list => 72 | { 73 | // 执行批量的 List 任务的方法 74 | // 这个传入的委托将会在缓存有数据时被调用,每次调用的时候传入的 list 列表至少存在一个元素 75 | }); 76 | 77 | // 其他线程调用 AddTask 方法加入任务 78 | doubleBufferTask.AddTask(new Foo()); 79 | 80 | // 在业务端完成之后,调用 Finish 方法表示不再有任务加入 81 | // 此 Finish 方法非线程安全,必须业务端根据业务调用 82 | doubleBufferTask.Finish(); 83 | 84 | // 其他线程可以调用 WaitAllTaskFinish 等待缓存所有任务执行完成 85 | // 在调用 Finish 方法之后,缓存的所有任务被全部执行之后将会返回 86 | await doubleBufferTask.WaitAllTaskFinish(); 87 | ``` 88 | 89 | 详细请看 [dotnet 双缓存数据结构设计 下载库的文件写入缓存框架](https://blog.lindexi.com/post/dotnet-%E5%8F%8C%E7%BC%93%E5%AD%98%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E8%AE%BE%E8%AE%A1-%E4%B8%8B%E8%BD%BD%E5%BA%93%E7%9A%84%E6%96%87%E4%BB%B6%E5%86%99%E5%85%A5%E7%BC%93%E5%AD%98%E6%A1%86%E6%9E%B6.html ) 90 | 91 | ### AsyncAutoResetEvent 92 | 93 | 异步版本的 AutoResetEvent 锁 94 | 95 | 功能上和 AutoResetEvent 相同,只是将 WaitOne 替换为 WaitOneAsync 用于支持异步等待 96 | 97 | 详细请看 [C# dotnet 高性能多线程工具 AsyncAutoResetEvent 异步等待使用方法和原理](https://blog.lindexi.com/post/C-dotnet-%E9%AB%98%E6%80%A7%E8%83%BD%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%B7%A5%E5%85%B7-AsyncAutoResetEvent-%E5%BC%82%E6%AD%A5%E7%AD%89%E5%BE%85%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95%E5%92%8C%E5%8E%9F%E7%90%86.html ) 98 | 99 | ### AsyncManualResetEvent 100 | 101 | 异步版本的 ManualResetEvent 锁 102 | 103 | 功能上和 ManualResetEvent 相同,只是将 WaitOne 替换为 WaitOneAsync 用于支持异步等待 104 | 105 | ### ExecuteOnceAwaiter 106 | 107 | 支持本机内多线程调用某一确定的任务的执行,任务仅执行一次,多次调用均返回相同结果 108 | 109 | 在任务执行完成之后,可以重置任务状态,让任务再次执行 110 | 111 | 如用来作为执行 同步 这个业务的工具。也就是在 同步 这个业务执行过程中,不允许再次执行 同步 这个业务。同时只要同步过了,那么再次调用只是返回同步结果。只有在同步之后状态发生变更之后,才能再次同步 112 | 113 | 详细请看 [C# dotnet 高性能多线程工具 ExecuteOnceAwaiter 只执行一次的任务](https://lindexi.gitee.io/post/C-dotnet-%E9%AB%98%E6%80%A7%E8%83%BD%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%B7%A5%E5%85%B7-ExecuteOnceAwaiter-%E5%8F%AA%E6%89%A7%E8%A1%8C%E4%B8%80%E6%AC%A1%E7%9A%84%E4%BB%BB%E5%8A%A1.html ) -------------------------------------------------------------------------------- /build/Version.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1.1.3 4 | 5 | -------------------------------------------------------------------------------- /docs/Benchmark.md: -------------------------------------------------------------------------------- 1 | # Benchmark 2 | 3 | ## Environment 4 | 5 | ``` ini 6 | 7 | BenchmarkDotNet=v0.12.0, OS=Windows 10.0.19041 8 | Intel Core i7-6700 CPU 3.40GHz (Skylake), 1 CPU, 8 logical and 4 physical cores 9 | .NET Core SDK=3.1.402 10 | [Host] : .NET Core 3.1.8 (CoreCLR 4.700.20.41105, CoreFX 4.700.20.41903), X64 RyuJIT [AttachedDebugger] 11 | 12 | Job=InProcess Toolchain=InProcessEmitToolchain 13 | 14 | ``` 15 | 16 | ## Write and Read 17 | 18 | | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | 19 | |-------------------------------- |---------:|--------:|--------:|------:|--------:|--------:|-------:|------:|----------:| 20 | | AsyncQueueEnqueueAndDequeueTest | 285.4 us | 5.54 us | 6.59 us | 2.22 | 0.06 | 26.3672 | 0.4883 | - | 104.51 KB | 21 | | ChannelReadAndWriteTest | 128.4 us | 2.55 us | 2.39 us | 1.00 | 0.00 | 4.1504 | - | - | 17.15 KB | 22 | 23 | 24 | ### AsyncQueue with multi-thread 25 | 26 | | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | 27 | |----------------------------------------------- |-----------:|---------:|---------:|------:|--------:|--------:|-------:|------:|----------:| 28 | | DoubleBufferTaskReadAndWrite | 2,995.9 us | 55.31 us | 54.32 us | 22.89 | 0.82 | 15.6250 | - | - | 70.68 KB | 29 | | DoubleBufferTaskWithCapacityReadAndWrite | 3,005.9 us | 59.24 us | 74.92 us | 22.96 | 0.72 | 19.5313 | - | - | 86.29 KB | 30 | | AsyncQueueEnqueueAndDequeueTest | 141.6 us | 2.76 us | 3.68 us | 1.08 | 0.03 | 25.1465 | 2.4414 | - | 103.53 KB | 31 | | AsyncQueueEnqueueAndDequeueTestWithMultiThread | 284.4 us | 5.63 us | 7.52 us | 2.17 | 0.07 | 26.3672 | 2.4414 | - | 104.55 KB | 32 | | ChannelReadAndWriteTest | 130.9 us | 2.55 us | 3.41 us | 1.00 | 0.00 | 4.1504 | - | - | 17.15 KB | 33 | | ChannelReadAndWriteTestWithMultiThread | 273.9 us | 4.98 us | 4.66 us | 2.10 | 0.07 | 3.9063 | - | - | 17.83 KB | 34 | 35 | ### DoubleBufferTask with multi-thread 36 | 37 | | Method | threadCount | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | 38 | |-------------------------------------------- |------------ |-----------:|---------:|---------:|------:|--------:|--------:|-------:|------:|----------:| 39 | | DoubleBufferTaskReadAndWrite | ? | 2,895.6 us | 39.62 us | 37.06 us | 22.65 | 0.46 | 15.6250 | - | - | 70.68 KB | 40 | | DoubleBufferTaskWithCapacityReadAndWrite | ? | 2,914.2 us | 50.76 us | 47.48 us | 22.80 | 0.42 | 19.5313 | - | - | 86.29 KB | 41 | | AsyncQueueEnqueueAndDequeueTest | ? | 275.4 us | 5.35 us | 5.73 us | 2.15 | 0.05 | 26.3672 | 0.4883 | - | 104.48 KB | 42 | | ChannelReadAndWriteTest | ? | 127.8 us | 2.06 us | 1.92 us | 1.00 | 0.00 | 4.1504 | - | - | 17.15 KB | 43 | | | | | | | | | | | | | 44 | | **DoubleBufferTaskWithMultiThreadReadAndWrite** | **2** | **2,068.5 us** | **40.93 us** | **58.70 us** | **?** | **?** | **19.5313** | **-** | **-** | **87.7 KB** | 45 | | | | | | | | | | | | | 46 | | **DoubleBufferTaskWithMultiThreadReadAndWrite** | **5** | **1,193.8 us** | **23.31 us** | **39.59 us** | **?** | **?** | **21.4844** | **-** | **-** | **88.33 KB** | 47 | | | | | | | | | | | | | 48 | | **DoubleBufferTaskWithMultiThreadReadAndWrite** | **10** | **1,120.2 us** | **22.31 us** | **28.21 us** | **?** | **?** | **21.4844** | **-** | **-** | **89.38 KB** | 49 | 50 | ### DoubleBufferTask with Batch task 51 | 52 | | Method | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated | 53 | |------------------------------------------------ |-------------:|----------:|----------:|------:|------:|------:|------:|----------:| 54 | | DoubleBufferTaskReadAndWriteTestWithMultiThread | 31.50 ms | 0.597 ms | 0.587 ms | 0.002 | - | - | - | 90.67 KB | 55 | | ChannelReadAndWriteTestWithMultiThread | 15,791.17 ms | 43.934 ms | 41.095 ms | 1.000 | - | - | - | 645.11 KB | 56 | 57 | 58 | 59 | ## DoubleBuffer Add task 60 | 61 | | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | 62 | |--------------------------------------------------------------- |------------:|------------:|------------:|-------:|--------:|--------:|--------:|--------:|----------:| 63 | | AddTaskToConcurrentBag | 539.1 us | 10.09 us | 9.91 us | 1.00 | 0.00 | 54.6875 | 30.2734 | 27.3438 | 256.45 KB | 64 | | AddTaskToConcurrentBagWithMultiThread | 857.0 us | 16.84 us | 18.72 us | 1.59 | 0.05 | 35.1563 | 17.5781 | 3.9063 | 163.54 KB | 65 | | AddTaskToDoubleBufferWithLock | 259.0 us | 2.98 us | 2.64 us | 0.48 | 0.01 | 37.5977 | 9.2773 | - | 156.45 KB | 66 | | AddTaskToDoubleBufferWithLockMultiThread | 599.9 us | 7.60 us | 6.74 us | 1.11 | 0.02 | 38.0859 | 8.7891 | - | 159.63 KB | 67 | | AddTaskToDoubleBufferWithReaderWriterLockSlim | 485.8 us | 9.63 us | 9.89 us | 0.90 | 0.02 | 37.5977 | 9.2773 | - | 156.55 KB | 68 | | AddTaskToDoubleBufferWithReaderWriterLockSlimMultiThread | 62,228.6 us | 2,209.10 us | 6,513.57 us | 118.39 | 13.81 | - | - | - | 160.15 KB | 69 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Benchmarks/AsyncWorkerCollection.Benchmarks.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Benchmarks/BatchProducerAndConsumerDoubleBufferReadAndWriteTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using BenchmarkDotNet.Attributes; 5 | using dotnetCampus.Threading; 6 | 7 | namespace AsyncWorkerCollection.Benchmarks 8 | { 9 | /// 10 | /// 批量任务的双缓存性能对比 11 | /// 12 | [BenchmarkCategory(nameof(BatchProducerAndConsumerDoubleBufferReadAndWriteTests))] 13 | public class BatchProducerAndConsumerDoubleBufferReadAndWriteTests 14 | { 15 | [Benchmark()] 16 | public async Task DoubleBufferTaskReadAndWriteTestWithMultiThread() 17 | { 18 | const int threadCount = 1; 19 | 20 | var doubleBufferTask = new DoubleBufferTask, Foo>(new List(MaxCount), 21 | new List(MaxCount), async list => 22 | { 23 | await StartDo(); 24 | }); 25 | var foo = new Foo(); 26 | 27 | var taskList = new Task[threadCount]; 28 | 29 | for (int j = 0; j < threadCount; j++) 30 | { 31 | var task = Task.Run(() => 32 | { 33 | for (int i = 0; i < MaxCount / threadCount; i++) 34 | { 35 | doubleBufferTask.AddTask(foo); 36 | } 37 | }); 38 | taskList[j] = task; 39 | } 40 | 41 | await Task.WhenAll(taskList); 42 | 43 | doubleBufferTask.Finish(); 44 | await doubleBufferTask.WaitAllTaskFinish(); 45 | } 46 | 47 | [Benchmark(Baseline = true)] 48 | public async Task ChannelReadAndWriteTestWithMultiThread() 49 | { 50 | var foo = new Foo(); 51 | var bounded = System.Threading.Channels.Channel.CreateBounded(MaxCount); 52 | 53 | var task = Task.Run(async () => 54 | { 55 | int n = 0; 56 | 57 | await foreach (var temp in bounded.Reader.ReadAllAsync()) 58 | { 59 | await StartDo(); 60 | n++; 61 | if (n == MaxCount) 62 | { 63 | break; 64 | } 65 | } 66 | }); 67 | 68 | for (int i = 0; i < MaxCount; i++) 69 | { 70 | await bounded.Writer.WriteAsync(foo); 71 | } 72 | 73 | await task; 74 | } 75 | 76 | /// 77 | /// 开始执行,如文件写入等,无论是写入多少条,都需要有开始的时间 78 | /// 79 | private async Task StartDo() 80 | { 81 | await Task.Delay(TimeSpan.FromMilliseconds(10)); 82 | } 83 | 84 | private const int MaxCount = 1000; 85 | 86 | class Foo 87 | { 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Benchmarks/DoubleBufferAddTaskTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using BenchmarkDotNet.Attributes; 7 | using dotnetCampus.Threading; 8 | 9 | namespace AsyncWorkerCollection.Benchmarks 10 | { 11 | /// 12 | /// 加入任务时的性能测试 13 | /// 14 | public class DoubleBufferAddTaskTests 15 | { 16 | [Benchmark(Baseline = true)] 17 | public void AddTaskToConcurrentBag() 18 | { 19 | var foo = new Foo(); 20 | var concurrentBag = new ConcurrentBag(); 21 | 22 | for (int i = 0; i < MaxCount; i++) 23 | { 24 | concurrentBag.Add(foo); 25 | } 26 | } 27 | 28 | /// 29 | /// 多线程加入数据到 ConcurrentBag 的方法 30 | /// 31 | [Benchmark()] 32 | public async Task AddTaskToConcurrentBagWithMultiThread() 33 | { 34 | var foo = new Foo(); 35 | var concurrentBag = new ConcurrentBag(); 36 | 37 | var threadCount = 10; 38 | 39 | var taskList = new Task[threadCount]; 40 | 41 | for (int j = 0; j < threadCount; j++) 42 | { 43 | var task = Task.Run(() => 44 | { 45 | for (int i = 0; i < MaxCount / threadCount; i++) 46 | { 47 | concurrentBag.Add(foo); 48 | } 49 | }); 50 | taskList[j] = task; 51 | } 52 | 53 | await Task.WhenAll(taskList); 54 | } 55 | 56 | [Benchmark()] 57 | public void AddTaskToDoubleBufferWithLock() 58 | { 59 | var foo = new Foo(); 60 | var doubleBuffer = new DoubleBuffer, Foo>(new List(MaxCount), new List(MaxCount)); 61 | 62 | for (int i = 0; i < MaxCount; i++) 63 | { 64 | doubleBuffer.Add(foo); 65 | } 66 | } 67 | 68 | [Benchmark()] 69 | public async Task AddTaskToDoubleBufferWithLockMultiThread() 70 | { 71 | var foo = new Foo(); 72 | var doubleBuffer = new DoubleBuffer, Foo>(new List(MaxCount), new List(MaxCount)); 73 | 74 | var threadCount = 10; 75 | 76 | var taskList = new Task[threadCount]; 77 | 78 | for (int j = 0; j < threadCount; j++) 79 | { 80 | var task = Task.Run(() => 81 | { 82 | for (int i = 0; i < MaxCount / threadCount; i++) 83 | { 84 | doubleBuffer.Add(foo); 85 | } 86 | }); 87 | taskList[j] = task; 88 | } 89 | 90 | await Task.WhenAll(taskList); 91 | } 92 | 93 | /// 94 | /// 没有给定数组的长度 95 | /// 96 | /// 97 | [Benchmark()] 98 | public async Task AddTaskToDoubleBufferWithoutCapacityMultiThread() 99 | { 100 | var foo = new Foo(); 101 | var doubleBuffer = new DoubleBuffer(); 102 | 103 | var threadCount = 10; 104 | 105 | var taskList = new Task[threadCount]; 106 | 107 | for (int j = 0; j < threadCount; j++) 108 | { 109 | var task = Task.Run(() => 110 | { 111 | for (int i = 0; i < MaxCount / threadCount; i++) 112 | { 113 | doubleBuffer.Add(foo); 114 | } 115 | }); 116 | taskList[j] = task; 117 | } 118 | 119 | await Task.WhenAll(taskList); 120 | } 121 | 122 | /// 123 | /// 使用链表的双缓存 124 | /// 125 | /// 126 | [Benchmark()] 127 | public async Task AddTaskToDoubleBufferWithLinkedListMultiThread() 128 | { 129 | var foo = new Foo(); 130 | 131 | var doubleBuffer = new DoubleBuffer, Foo>(new LinkedList(), new LinkedList()); 132 | 133 | var threadCount = 10; 134 | 135 | var taskList = new Task[threadCount]; 136 | 137 | for (int j = 0; j < threadCount; j++) 138 | { 139 | var task = Task.Run(() => 140 | { 141 | for (int i = 0; i < MaxCount / threadCount; i++) 142 | { 143 | doubleBuffer.Add(foo); 144 | } 145 | }); 146 | taskList[j] = task; 147 | } 148 | 149 | await Task.WhenAll(taskList); 150 | } 151 | 152 | [Benchmark()] 153 | public void AddTaskToLegacyDoubleBufferWithReaderWriterLockSlim() 154 | { 155 | var foo = new Foo(); 156 | var doubleBuffer = 157 | new DoubleBufferWithReaderWriterLockSlim, Foo>(new List(MaxCount), 158 | new List(MaxCount)); 159 | 160 | for (int i = 0; i < MaxCount; i++) 161 | { 162 | doubleBuffer.Add(foo); 163 | } 164 | } 165 | 166 | [Benchmark()] 167 | public async Task AddTaskToLegacyDoubleBufferWithReaderWriterLockSlimMultiThread() 168 | { 169 | var foo = new Foo(); 170 | var doubleBuffer = 171 | new DoubleBufferWithReaderWriterLockSlim, Foo>(new List(MaxCount), 172 | new List(MaxCount)); 173 | 174 | var threadCount = 10; 175 | 176 | var taskList = new Task[threadCount]; 177 | 178 | for (int j = 0; j < threadCount; j++) 179 | { 180 | var task = Task.Run(() => 181 | { 182 | for (int i = 0; i < MaxCount / threadCount; i++) 183 | { 184 | doubleBuffer.Add(foo); 185 | } 186 | }); 187 | taskList[j] = task; 188 | } 189 | 190 | await Task.WhenAll(taskList); 191 | } 192 | 193 | private const int MaxCount = 10000; 194 | 195 | class Foo 196 | { 197 | } 198 | 199 | /// 200 | /// 使用读者写者锁的方法,因为在 Add 的时候,是允许多个线程一起写入的,尽管下面代码没有处理多线程同时写入的坑 201 | /// 202 | /// 203 | /// 204 | /// 但是性能测试发现使用读者写者锁的性能更差 205 | /* 206 | BenchmarkDotNet=v0.12.0, OS=Windows 10.0.19041 207 | Intel Core i7-6700 CPU 3.40GHz (Skylake), 1 CPU, 8 logical and 4 physical cores 208 | .NET Core SDK=3.1.402 209 | [Host] : .NET Core 3.1.8 (CoreCLR 4.700.20.41105, CoreFX 4.700.20.41903), X64 RyuJIT [AttachedDebugger] 210 | 211 | Job=InProcess Toolchain=InProcessEmitToolchain 212 | 213 | | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | 214 | |--------------------------------------------------------------- |------------:|------------:|------------:|-------:|--------:|--------:|--------:|--------:|----------:| 215 | | AddTaskToConcurrentBag | 539.1 us | 10.09 us | 9.91 us | 1.00 | 0.00 | 54.6875 | 30.2734 | 27.3438 | 256.45 KB | 216 | | AddTaskToConcurrentBagWithMultiThread | 857.0 us | 16.84 us | 18.72 us | 1.59 | 0.05 | 35.1563 | 17.5781 | 3.9063 | 163.54 KB | 217 | | AddTaskToDoubleBufferWithLock | 259.0 us | 2.98 us | 2.64 us | 0.48 | 0.01 | 37.5977 | 9.2773 | - | 156.45 KB | 218 | | AddTaskToDoubleBufferWithLockMultiThread | 599.9 us | 7.60 us | 6.74 us | 1.11 | 0.02 | 38.0859 | 8.7891 | - | 159.63 KB | 219 | | AddTaskToDoubleBufferWithReaderWriterLockSlim | 485.8 us | 9.63 us | 9.89 us | 0.90 | 0.02 | 37.5977 | 9.2773 | - | 156.55 KB | 220 | | AddTaskToDoubleBufferWithReaderWriterLockSlimMultiThread | 62,228.6 us | 2,209.10 us | 6,513.57 us | 118.39 | 13.81 | - | - | - | 160.15 KB | 221 | */ 222 | class DoubleBufferWithReaderWriterLockSlim where T : class, ICollection 223 | { 224 | /// 225 | /// 创建双缓存 226 | /// 227 | /// 228 | /// 229 | public DoubleBufferWithReaderWriterLockSlim(T aList, T bList) 230 | { 231 | AList = aList; 232 | BList = bList; 233 | 234 | CurrentList = AList; 235 | } 236 | 237 | /// 238 | /// 加入元素到缓存 239 | /// 240 | /// 241 | public void Add(TU t) 242 | { 243 | _readerWriterLockSlim.EnterReadLock(); 244 | try 245 | { 246 | CurrentList.Add(t); 247 | } 248 | finally 249 | { 250 | _readerWriterLockSlim.ExitReadLock(); 251 | } 252 | } 253 | 254 | /// 255 | /// 切换缓存 256 | /// 257 | /// 258 | public T SwitchBuffer() 259 | { 260 | _readerWriterLockSlim.EnterWriteLock(); 261 | try 262 | { 263 | if (ReferenceEquals(CurrentList, AList)) 264 | { 265 | CurrentList = BList; 266 | return AList; 267 | } 268 | else 269 | { 270 | CurrentList = AList; 271 | return BList; 272 | } 273 | } 274 | finally 275 | { 276 | _readerWriterLockSlim.ExitWriteLock(); 277 | } 278 | } 279 | 280 | /// 281 | /// 执行完所有任务 282 | /// 283 | /// 当前缓存里面存在的任务,请不要保存传入的 List 参数 284 | public void DoAll(Action action) 285 | { 286 | while (true) 287 | { 288 | var buffer = SwitchBuffer(); 289 | if (buffer.Count == 0) break; 290 | 291 | action(buffer); 292 | buffer.Clear(); 293 | } 294 | } 295 | 296 | /// 297 | /// 执行完所有任务 298 | /// 299 | /// 当前缓存里面存在的任务,请不要保存传入的 List 参数 300 | /// 301 | public async Task DoAllAsync(Func action) 302 | { 303 | while (true) 304 | { 305 | var buffer = SwitchBuffer(); 306 | if (buffer.Count == 0) break; 307 | 308 | await action(buffer); 309 | buffer.Clear(); 310 | } 311 | } 312 | 313 | private readonly ReaderWriterLockSlim _readerWriterLockSlim = new ReaderWriterLockSlim(); 314 | 315 | private T CurrentList { set; get; } 316 | 317 | private T AList { get; } 318 | private T BList { get; } 319 | } 320 | } 321 | } 322 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Benchmarks/ProducerAndConsumerAsyncQueueReadAndWriteTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using BenchmarkDotNet.Attributes; 4 | using dotnetCampus.Threading; 5 | 6 | namespace AsyncWorkerCollection.Benchmarks 7 | { 8 | /// 9 | /// 生产者消费者同时进行读写的测试 10 | /// 11 | [BenchmarkCategory(nameof(ProducerAndConsumerAsyncQueueReadAndWriteTests))] 12 | public class ProducerAndConsumerAsyncQueueReadAndWriteTests 13 | { 14 | [Benchmark()] 15 | public async Task DoubleBufferTaskReadAndWrite() 16 | { 17 | var doubleBufferTask = new DoubleBufferTask(list => Task.CompletedTask); 18 | var foo = new Foo(); 19 | 20 | for (int i = 0; i < MaxCount; i++) 21 | { 22 | doubleBufferTask.AddTask(foo); 23 | } 24 | 25 | doubleBufferTask.Finish(); 26 | await doubleBufferTask.WaitAllTaskFinish(); 27 | } 28 | 29 | [Benchmark()] 30 | public async Task DoubleBufferTaskWithCapacityReadAndWrite() 31 | { 32 | var doubleBufferTask = new DoubleBufferTask, Foo>(new List(MaxCount), 33 | new List(MaxCount), list => Task.CompletedTask); 34 | var foo = new Foo(); 35 | 36 | for (int i = 0; i < MaxCount; i++) 37 | { 38 | doubleBufferTask.AddTask(foo); 39 | } 40 | 41 | doubleBufferTask.Finish(); 42 | await doubleBufferTask.WaitAllTaskFinish(); 43 | } 44 | 45 | [Benchmark()] 46 | [Arguments(2)] 47 | [Arguments(5)] 48 | [Arguments(10)] 49 | public async Task DoubleBufferTaskWithMultiThreadReadAndWrite(int threadCount) 50 | { 51 | var doubleBufferTask = new DoubleBufferTask, Foo>(new List(MaxCount), 52 | new List(MaxCount), list => Task.CompletedTask); 53 | var foo = new Foo(); 54 | 55 | var taskList = new Task[threadCount]; 56 | 57 | for (int j = 0; j < threadCount; j++) 58 | { 59 | var task = Task.Run(() => 60 | { 61 | for (int i = 0; i < MaxCount / threadCount; i++) 62 | { 63 | doubleBufferTask.AddTask(foo); 64 | } 65 | }); 66 | taskList[j] = task; 67 | } 68 | 69 | await Task.WhenAll(taskList); 70 | 71 | doubleBufferTask.Finish(); 72 | await doubleBufferTask.WaitAllTaskFinish(); 73 | } 74 | 75 | [Benchmark()] 76 | public async Task AsyncQueueEnqueueAndDequeueTest() 77 | { 78 | var asyncQueue = new AsyncQueue(); 79 | var foo = new Foo(); 80 | 81 | for (int i = 0; i < MaxCount; i++) 82 | { 83 | asyncQueue.Enqueue(foo); 84 | } 85 | 86 | for (int i = 0; i < MaxCount; i++) 87 | { 88 | var temp = await asyncQueue.DequeueAsync(); 89 | } 90 | } 91 | 92 | [Benchmark()] 93 | public async Task AsyncQueueEnqueueAndDequeueTestWithMultiThread() 94 | { 95 | var asyncQueue = new AsyncQueue(); 96 | var foo = new Foo(); 97 | var task = Task.Run(async () => 98 | { 99 | int n = 0; 100 | while (true) 101 | { 102 | n++; 103 | if (n == MaxCount) 104 | { 105 | break; 106 | } 107 | 108 | var temp = await asyncQueue.DequeueAsync(); 109 | if (temp is null) 110 | { 111 | return; 112 | } 113 | } 114 | }); 115 | 116 | for (int i = 0; i < MaxCount; i++) 117 | { 118 | asyncQueue.Enqueue(foo); 119 | } 120 | 121 | await task; 122 | } 123 | 124 | [Benchmark(Baseline = true)] 125 | public async Task ChannelReadAndWriteTest() 126 | { 127 | var foo = new Foo(); 128 | var bounded = System.Threading.Channels.Channel.CreateBounded(MaxCount); 129 | 130 | for (int i = 0; i < MaxCount; i++) 131 | { 132 | await bounded.Writer.WriteAsync(foo); 133 | } 134 | 135 | int n = 0; 136 | 137 | await foreach (var temp in bounded.Reader.ReadAllAsync()) 138 | { 139 | n++; 140 | if (n == MaxCount) 141 | { 142 | break; 143 | } 144 | } 145 | } 146 | 147 | [Benchmark()] 148 | public async Task ChannelReadAndWriteTestWithMultiThread() 149 | { 150 | var foo = new Foo(); 151 | var bounded = System.Threading.Channels.Channel.CreateBounded(MaxCount); 152 | 153 | var task = Task.Run(async () => 154 | { 155 | int n = 0; 156 | 157 | await foreach (var temp in bounded.Reader.ReadAllAsync()) 158 | { 159 | n++; 160 | if (n == MaxCount) 161 | { 162 | break; 163 | } 164 | } 165 | }); 166 | 167 | for (int i = 0; i < MaxCount; i++) 168 | { 169 | await bounded.Writer.WriteAsync(foo); 170 | } 171 | 172 | await task; 173 | } 174 | 175 | private const int MaxCount = 1000; 176 | 177 | class Foo 178 | { 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Benchmarks/ProducerAndConsumerAsyncQueueWriteTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using BenchmarkDotNet.Attributes; 3 | using dotnetCampus.Threading; 4 | 5 | namespace AsyncWorkerCollection.Benchmarks 6 | { 7 | /// 8 | /// 生产者消费者仅写入的测试 9 | /// 10 | [BenchmarkCategory(nameof(ProducerAndConsumerAsyncQueueWriteTests))] 11 | public class ProducerAndConsumerAsyncQueueWriteTests 12 | { 13 | [Benchmark()] 14 | public void AsyncQueueEnqueueTest() 15 | { 16 | var asyncQueue = new AsyncQueue(); 17 | 18 | var foo = new Foo(); 19 | for (int i = 0; i < MaxCount; i++) 20 | { 21 | asyncQueue.Enqueue(foo); 22 | } 23 | } 24 | 25 | [Benchmark(Baseline = true)] 26 | public async Task ChannelWriteAsyncTest() 27 | { 28 | var foo = new Foo(); 29 | var bounded = System.Threading.Channels.Channel.CreateBounded(MaxCount); 30 | 31 | for (int i = 0; i < MaxCount; i++) 32 | { 33 | await bounded.Writer.WriteAsync(foo); 34 | } 35 | } 36 | 37 | private const int MaxCount = 1000; 38 | 39 | class Foo 40 | { 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Benchmarks/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using BenchmarkDotNet.Configs; 4 | using BenchmarkDotNet.Diagnosers; 5 | using BenchmarkDotNet.Exporters; 6 | using BenchmarkDotNet.Jobs; 7 | using BenchmarkDotNet.Loggers; 8 | using BenchmarkDotNet.Running; 9 | 10 | namespace AsyncWorkerCollection.Benchmarks 11 | { 12 | class Program 13 | { 14 | static void Main(string[] args) 15 | { 16 | var switcher = new BenchmarkSwitcher(typeof(Program).Assembly); 17 | var config = GetConfig(args); 18 | switcher.Run(new[] { "--filter", "*" }, config); 19 | } 20 | 21 | private static IConfig GetConfig(string[] args) 22 | { 23 | var config = new CustomConfig(); 24 | 25 | if (args.Length > 0) 26 | { 27 | return config.WithArtifactsPath(args[0]); 28 | } 29 | else 30 | { 31 | return config; 32 | } 33 | } 34 | 35 | private class CustomConfig : ManualConfig 36 | { 37 | public CustomConfig() 38 | { 39 | // Diagnosers 40 | Add(MemoryDiagnoser.Default); 41 | 42 | // Columns 43 | Add(DefaultConfig.Instance.GetColumnProviders().ToArray()); 44 | 45 | // Loggers 46 | Add(ConsoleLogger.Default); 47 | 48 | // Exporters 49 | Add(MarkdownExporter.GitHub); 50 | 51 | Add(Job.InProcess); 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/AsyncAutoResetEventTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using dotnetCampus.Threading; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using Moq; 9 | using MSTest.Extensions.Contracts; 10 | 11 | namespace AsyncWorkerCollection.Tests 12 | { 13 | [TestClass] 14 | public class AsyncAutoResetEventTests 15 | { 16 | [ContractTestCase] 17 | public void WaitForSuccessOrResult() 18 | { 19 | "当使用 Set 次数超过 WaitOneAsync 次数,多余的 Set 只被计算一次".Test(() => 20 | { 21 | // Arrange 22 | var asyncAutoResetEvent = new AsyncAutoResetEvent(false); 23 | var mock = new Mock(); 24 | 25 | // Action 26 | // 先加入一个等待的线程,用于等待第一次的 Set 对应的等待 27 | var manualResetEvent = new ManualResetEvent(false); 28 | var task1 = Task.Run(async () => 29 | { 30 | var task = asyncAutoResetEvent.WaitOneAsync(); 31 | manualResetEvent.Set(); 32 | await task; 33 | mock.Object.Do(); 34 | }); 35 | // 使用 manualResetEvent 可以等待让 task1 执行到了 WaitOne 方法 36 | manualResetEvent.WaitOne(); 37 | 38 | for (var i = 0; i < 5; i++) 39 | { 40 | asyncAutoResetEvent.Set(); 41 | } 42 | 43 | var taskList = new List(); 44 | for (var i = 0; i < 5; i++) 45 | { 46 | var task = Task.Run(async () => 47 | { 48 | Console.WriteLine("进入调用"); 49 | await asyncAutoResetEvent.WaitOneAsync(); 50 | mock.Object.Do(); 51 | }); 52 | taskList.Add(task); 53 | } 54 | 55 | foreach (var task in taskList) 56 | { 57 | Task.WaitAny(task, Task.Delay(TimeSpan.FromSeconds(1))); 58 | } 59 | 60 | // Assert 61 | mock.Verify(job => job.Do(), Times.Exactly(2)); 62 | }); 63 | 64 | "在先设置 Set 然后再 WaitOneAsync 只有一个线程执行".Test(() => 65 | { 66 | // Arrange 67 | var asyncAutoResetEvent = new AsyncAutoResetEvent(false); 68 | var mock = new Mock(); 69 | 70 | // Action 71 | asyncAutoResetEvent.Set(); 72 | var task1 = Task.Run(async () => 73 | { 74 | await asyncAutoResetEvent.WaitOneAsync(); 75 | mock.Object.Do(); 76 | }); 77 | 78 | var task2 = Task.Run(async () => 79 | { 80 | await asyncAutoResetEvent.WaitOneAsync(); 81 | mock.Object.Do(); 82 | }); 83 | 84 | Task.WaitAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(1))); 85 | 86 | // Assert 87 | mock.Verify(job => job.Do(), Times.Once); 88 | }); 89 | 90 | "使用 AsyncAutoResetEvent 设置一次 Set 对应一次 WaitOneAsync 的线程执行".Test(() => 91 | { 92 | // Arrange 93 | var asyncAutoResetEvent = new AsyncAutoResetEvent(false); 94 | var mock = new Mock(); 95 | 96 | // Action 97 | var taskList = new List(10); 98 | // 使用 SemaphoreSlim 让测试线程全部创建 99 | var semaphoreSlim = new SemaphoreSlim(0, 10); 100 | for (var i = 0; i < 10; i++) 101 | { 102 | var task = Task.Run(async () => 103 | { 104 | var t = asyncAutoResetEvent.WaitOneAsync(); 105 | semaphoreSlim.Release(); 106 | await t; 107 | mock.Object.Do(); 108 | }); 109 | taskList.Add(task); 110 | } 111 | 112 | // 等待 Task 都进入 await 方法 113 | // 如果没有等待,可以都在线程创建上面,此时调用多次的 Set 只是做初始化 114 | // 也就是当前没有线程等待,然后进行多次 Set 方法 115 | for (int i = 0; i < 10; i++) 116 | { 117 | semaphoreSlim.Wait(); 118 | } 119 | 120 | for (var i = 0; i < 5; i++) 121 | { 122 | asyncAutoResetEvent.Set(); 123 | } 124 | 125 | foreach (var task in taskList) 126 | { 127 | Task.WaitAny(task, Task.Delay(TimeSpan.FromSeconds(1))); 128 | } 129 | 130 | // Assert 131 | mock.Verify(job => job.Do(), Times.Exactly(5)); 132 | }); 133 | 134 | "构造函数设置为 true 等待 WaitOneAsync 的线程会执行".Test(() => 135 | { 136 | // Arrange 137 | var asyncAutoResetEvent = new AsyncAutoResetEvent(true); 138 | var mock = new Mock(); 139 | 140 | // Action 141 | var task = Task.Run(async () => 142 | { 143 | await asyncAutoResetEvent.WaitOneAsync(); 144 | mock.Object.Do(); 145 | }); 146 | 147 | Task.WaitAny(task, Task.Delay(TimeSpan.FromSeconds(1))); 148 | 149 | // Assert 150 | mock.Verify(job => job.Do(), Times.Once); 151 | }); 152 | 153 | "构造函数设置为 false 等待 WaitOneAsync 的线程不会执行".Test(() => 154 | { 155 | // Arrange 156 | var asyncAutoResetEvent = new AsyncAutoResetEvent(false); 157 | var mock = new Mock(); 158 | 159 | // Action 160 | var task = Task.Run(async () => 161 | { 162 | await asyncAutoResetEvent.WaitOneAsync(); 163 | mock.Object.Do(); 164 | }); 165 | 166 | Task.WaitAny(task, Task.Delay(TimeSpan.FromSeconds(1))); 167 | 168 | // Assert 169 | mock.Verify(job => job.Do(), Times.Never); 170 | }); 171 | 172 | "在 WaitOne 之前调用多次 Set 只有在调用之后让一个 WaitOne 方法继续".Test(() => 173 | { 174 | using var asyncAutoResetEvent = new AsyncAutoResetEvent(false); 175 | for (int i = 0; i < 1000; i++) 176 | { 177 | asyncAutoResetEvent.Set(); 178 | } 179 | 180 | var count = 0; 181 | var taskList = new List(); 182 | for (int i = 0; i < 10; i++) 183 | { 184 | taskList.Add(Task.Run(async () => 185 | { 186 | // ReSharper disable once AccessToDisposedClosure 187 | await asyncAutoResetEvent.WaitOneAsync(); 188 | Interlocked.Increment(ref count); 189 | })); 190 | } 191 | 192 | // 只有一个执行 193 | // 单元测试有一个坑,也就是在不同的设备上,也许有设备就是不分配线程,所以这个单元测试也许会在执行的时候,发现没有一个线程执行完成 194 | taskList.Add(Task.Delay(TimeSpan.FromSeconds(5))); 195 | // 在上面加入一个等待 5 秒的线程,此时理论上有一个线程执行完成 196 | Task.WaitAny(taskList.ToArray()); 197 | // 什么时候是 0 的值?在没有分配线程,也就是没有一个 Task.Run 进入 198 | Assert.AreEqual(true, count <= 1); 199 | // 一定有超过 9 个线程没有执行完成 200 | Assert.AreEqual(true, taskList.Count(task => !task.IsCompleted) >= 9); 201 | }); 202 | } 203 | 204 | [ContractTestCase] 205 | public void ReleaseObject() 206 | { 207 | "在调用释放之后,所有的等待将会被释放,同时释放的值是 false 值".Test(() => 208 | { 209 | var asyncAutoResetEvent = new AsyncAutoResetEvent(false); 210 | var manualResetEvent = new ManualResetEvent(false); 211 | var task = Task.Run(async () => 212 | { 213 | // ReSharper disable once AccessToDisposedClosure 214 | var t = asyncAutoResetEvent.WaitOneAsync(); 215 | manualResetEvent.Set(); 216 | 217 | return await t; 218 | }); 219 | // 解决单元测试里面 Task.Run 启动太慢 220 | manualResetEvent.WaitOne(); 221 | asyncAutoResetEvent.Dispose(); 222 | 223 | task.Wait(); 224 | var taskResult = task.Result; 225 | Assert.AreEqual(false, taskResult); 226 | }); 227 | } 228 | 229 | public interface IFakeJob 230 | { 231 | void Do(); 232 | } 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/AsyncQueueTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Threading.Tasks; 5 | using dotnetCampus.Threading; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using MSTest.Extensions.Contracts; 8 | 9 | namespace AsyncWorkerCollection.Tests 10 | { 11 | [TestClass] 12 | public class AsyncQueueTest 13 | { 14 | [ContractTestCase] 15 | public void DisposeTest() 16 | { 17 | "调用 AsyncQueue 销毁方法,有 10 个线程在等待出队,将会释放当前所有在等待出队的任务".Test(async () => 18 | { 19 | // Arrange 20 | var asyncQueue = new AsyncQueue(); 21 | const int count = 10; 22 | var taskList = new Task[count]; 23 | for (int i = 0; i < count; i++) 24 | { 25 | var task = asyncQueue.DequeueAsync(); 26 | taskList[i] = task; 27 | } 28 | 29 | // Action 30 | asyncQueue.Dispose(); 31 | 32 | // 等待一下 DequeueAsync 逻辑的完成 33 | await Task.WhenAny(Task.WhenAll(taskList), Task.Delay(TimeSpan.FromSeconds(1))); 34 | 35 | // Assert 36 | foreach (var task in taskList) 37 | { 38 | Assert.AreEqual(true, task.IsCompleted); 39 | } 40 | }); 41 | 42 | "调用 AsyncQueue 销毁方法,有一个线程在等待出队,将会释放当前在等待出队的任务".Test(async () => 43 | { 44 | // Arrange 45 | var asyncQueue = new AsyncQueue(); 46 | var task1 = asyncQueue.DequeueAsync(); 47 | 48 | // Action 49 | asyncQueue.Dispose(); 50 | // 等待一下 DequeueAsync 逻辑的完成 51 | await Task.Delay(TimeSpan.FromSeconds(1)); 52 | 53 | // Assert 54 | Assert.AreEqual(true, task1.IsCompleted); 55 | }); 56 | 57 | "在 AsyncQueue 进行销毁之前,存在元素没有出队,调用销毁时可以成功销毁".Test(() => 58 | { 59 | // Arrange 60 | var asyncQueue = new AsyncQueue(); 61 | asyncQueue.Enqueue(0); 62 | asyncQueue.Enqueue(0); 63 | 64 | // Action 65 | asyncQueue.Dispose(); 66 | 67 | // Assert 68 | Assert.AreEqual(0, asyncQueue.Count); 69 | }); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/AsyncTaskQueueTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using dotnetCampus.Threading; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using MSTest.Extensions.Contracts; 7 | 8 | namespace AsyncWorkerCollection.Tests 9 | { 10 | [TestClass] 11 | public class AsyncTaskQueueTest 12 | { 13 | [ContractTestCase] 14 | public void DisposeTest() 15 | { 16 | "在执行任务时先加入新的任务再调用清理,可以成功清理".Test(async () => 17 | { 18 | AsyncTaskQueue asyncTaskQueue = 19 | new AsyncTaskQueue() { AutoCancelPreviousTask = true, UseSingleThread = true }; 20 | 21 | var task = asyncTaskQueue.ExecuteAsync(() => 22 | { 23 | _ = asyncTaskQueue.ExecuteAsync((Func) (() => Task.CompletedTask)); 24 | 25 | asyncTaskQueue.Dispose(); 26 | 27 | return Task.FromResult(1); 28 | }); 29 | 30 | var result = await task; 31 | // 没有抛出异常就是符合预期 32 | // 因为在清理的时候清空队列,因此第一个任务能成功 33 | Assert.AreEqual(true, result.IsInvalid); 34 | Assert.AreEqual(1, result.Result); 35 | }); 36 | 37 | "在执行任务时先调用清理再加入新的任务,可以成功清理".Test(async () => 38 | { 39 | AsyncTaskQueue asyncTaskQueue = 40 | new AsyncTaskQueue() { AutoCancelPreviousTask = true, UseSingleThread = true }; 41 | 42 | var task = asyncTaskQueue.ExecuteAsync(() => 43 | { 44 | // 先清理再加入任务 45 | asyncTaskQueue.Dispose(); 46 | _ = asyncTaskQueue.ExecuteAsync((Func) (() => Task.CompletedTask)); 47 | 48 | return Task.FromResult(1); 49 | }); 50 | 51 | var result = await task; 52 | // 没有抛出异常就是符合预期 53 | // 被清理之后加入的任务将啥都不做,因此第一个任务可以成功 54 | Assert.AreEqual(true, result.IsInvalid); 55 | Assert.AreEqual(1, result.Result); 56 | }); 57 | 58 | "在执行任务时,调用清理 AsyncTaskQueue 的逻辑,可以成功清理".Test(async () => 59 | { 60 | AsyncTaskQueue asyncTaskQueue = new AsyncTaskQueue() { AutoCancelPreviousTask = true, UseSingleThread = true }; 61 | 62 | var autoResetEvent1 = new AsyncAutoResetEvent(false); 63 | var autoResetEvent2 = new AsyncAutoResetEvent(false); 64 | 65 | var task = asyncTaskQueue.ExecuteAsync(async () => 66 | { 67 | // 让第二个任务加入 68 | autoResetEvent1.Set(); 69 | 70 | // 等待第二个任务加入完成 71 | await autoResetEvent2.WaitOneAsync(); 72 | 73 | asyncTaskQueue.Dispose(); 74 | return 1; 75 | }); 76 | 77 | await autoResetEvent1.WaitOneAsync(); 78 | _ = asyncTaskQueue.ExecuteAsync((Func) (() => Task.CompletedTask)); 79 | autoResetEvent2.Set(); 80 | 81 | var result = await task; 82 | // 没有抛出异常就是符合预期 83 | // 因为第二个任务的加入而让第一个任务失败 84 | Assert.AreEqual(false, result.IsInvalid); 85 | }); 86 | 87 | "连续开始任务的时候,无法立刻清理".Test(async () => 88 | { 89 | AsyncTaskQueue asyncTaskQueue = new AsyncTaskQueue() { AutoCancelPreviousTask = true, UseSingleThread = true }; 90 | 91 | var autoResetEvent = new AutoResetEvent(false); 92 | _ = Task.Run(() => 93 | { 94 | autoResetEvent.WaitOne(); 95 | asyncTaskQueue.Dispose(); 96 | }); 97 | 98 | var result = await asyncTaskQueue.ExecuteAsync(async () => 99 | { 100 | await Task.Delay(10); 101 | autoResetEvent.Set(); 102 | return 1; 103 | }); 104 | 105 | await Task.Delay(100); 106 | 107 | for (int i = 0; i < 10; i++) 108 | { 109 | _ = asyncTaskQueue.ExecuteAsync((Func) (() => Task.CompletedTask)); 110 | } 111 | 112 | await Task.Delay(1000); 113 | autoResetEvent.Set(); 114 | 115 | // 没有抛出异常就是符合预期 116 | Assert.AreEqual(true, result.IsInvalid); 117 | Assert.AreEqual(1, result.Result); 118 | }); 119 | 120 | "在执行任务结束的时候调用 AsyncTaskQueue 销毁方法,可以不抛异常销毁".Test(async () => 121 | { 122 | AsyncTaskQueue asyncTaskQueue = new AsyncTaskQueue() { AutoCancelPreviousTask = true, UseSingleThread = true }; 123 | var autoResetEvent = new AutoResetEvent(false); 124 | _ = Task.Run(() => 125 | { 126 | autoResetEvent.WaitOne(); 127 | asyncTaskQueue.Dispose(); 128 | }); 129 | 130 | var result = await asyncTaskQueue.ExecuteAsync(async () => 131 | { 132 | await Task.Delay(10); 133 | autoResetEvent.Set(); 134 | return 1; 135 | }); 136 | 137 | Thread.Sleep(2000); 138 | 139 | Assert.AreEqual(true, result.IsInvalid); 140 | Assert.AreEqual(1, result.Result); 141 | }); 142 | 143 | "调用 AsyncTaskQueue 销毁方法,可以不抛异常销毁".Test(async () => 144 | { 145 | AsyncTaskQueue asyncTaskQueue = new AsyncTaskQueue() { AutoCancelPreviousTask = true, UseSingleThread = true }; 146 | 147 | var result = await asyncTaskQueue.ExecuteAsync(async () => 148 | { 149 | await Task.Delay(10); 150 | return 0; 151 | }); 152 | 153 | asyncTaskQueue.Dispose(); 154 | 155 | Thread.Sleep(2000); 156 | 157 | Assert.AreEqual(true, result.IsInvalid); 158 | Assert.AreEqual(0, result.Result); 159 | }); 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/AsyncWorkerCollection.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1;net5 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/DoubleBufferTaskDoUtilInitializedTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using dotnetCampus.Threading; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using Moq; 6 | using MSTest.Extensions.Contracts; 7 | 8 | namespace AsyncWorkerCollection.Tests 9 | { 10 | [TestClass] 11 | public class DoubleBufferTaskDoUtilInitializedTest 12 | { 13 | [ContractTestCase] 14 | public void DoUtilInitialized() 15 | { 16 | "在调用初始化之后,才开始执行任务".Test(async () => 17 | { 18 | var mock = new Mock(); 19 | mock.Setup(worker => worker.DoTask(It.IsAny>())); 20 | 21 | var doubleBufferTaskDoUtilInitialized = new DoubleBufferLazyInitializeTask(mock.Object.DoTask); 22 | for (int i = 0; i < 100; i++) 23 | { 24 | doubleBufferTaskDoUtilInitialized.AddTask(i); 25 | } 26 | 27 | var taskList = new List(); 28 | 29 | for (int i = 0; i < 100; i++) 30 | { 31 | taskList.Add(Task.Run(() => doubleBufferTaskDoUtilInitialized.AddTask(0))); 32 | } 33 | 34 | await Task.WhenAll(taskList); 35 | doubleBufferTaskDoUtilInitialized.Finish(); 36 | 37 | var waitAllTaskFinish = doubleBufferTaskDoUtilInitialized.WaitAllTaskFinish(); 38 | 39 | mock.Verify(worker => worker.DoTask(It.IsAny>()), Times.Never); 40 | Assert.AreEqual(false, waitAllTaskFinish.IsCompleted); 41 | 42 | // 调用初始化完成 43 | doubleBufferTaskDoUtilInitialized.OnInitialized(); 44 | await waitAllTaskFinish; 45 | mock.Verify(worker => worker.DoTask(It.IsAny>()), Times.AtLeast(1)); 46 | }); 47 | 48 | "在调用初始化之前,不会执行任何的任务".Test(async () => 49 | { 50 | var mock = new Mock(); 51 | mock.Setup(worker => worker.DoTask(It.IsAny>())); 52 | 53 | var doubleBufferTaskDoUtilInitialized = new DoubleBufferLazyInitializeTask(mock.Object.DoTask); 54 | for (int i = 0; i < 100; i++) 55 | { 56 | doubleBufferTaskDoUtilInitialized.AddTask(i); 57 | } 58 | 59 | var taskList = new List(); 60 | 61 | for (int i = 0; i < 100; i++) 62 | { 63 | taskList.Add(Task.Run(() => doubleBufferTaskDoUtilInitialized.AddTask(0))); 64 | } 65 | 66 | await Task.WhenAll(taskList); 67 | doubleBufferTaskDoUtilInitialized.Finish(); 68 | 69 | var waitAllTaskFinish = doubleBufferTaskDoUtilInitialized.WaitAllTaskFinish(); 70 | 71 | mock.Verify(worker => worker.DoTask(It.IsAny>()), Times.Never); 72 | Assert.AreEqual(false, waitAllTaskFinish.IsCompleted); 73 | }); 74 | } 75 | 76 | public interface IWorker 77 | { 78 | Task DoTask(List list); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/DoubleBufferTaskTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using dotnetCampus.Threading; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using Moq; 7 | using MSTest.Extensions.Contracts; 8 | 9 | namespace AsyncWorkerCollection.Tests 10 | { 11 | [TestClass] 12 | public class DoubleBufferTaskTest 13 | { 14 | [ContractTestCase] 15 | public void Finish() 16 | { 17 | "在设置 DoubleBufferTask 的 Finish 方法之后,调用 AddTask 加入任务将会抛出异常".Test(() => 18 | { 19 | var mock = new Mock(); 20 | mock.Setup(foo => foo.Foo()); 21 | var asyncManualResetEvent = new AsyncManualResetEvent(false); 22 | 23 | var doubleBufferTask = new DoubleBufferTask(async list => 24 | { 25 | await asyncManualResetEvent.WaitOneAsync(); 26 | 27 | foreach (var foo in list) 28 | { 29 | foo.Foo(); 30 | } 31 | }); 32 | 33 | doubleBufferTask.Finish(); 34 | 35 | Assert.ThrowsException(() => 36 | { 37 | doubleBufferTask.AddTask(mock.Object); 38 | }); 39 | }); 40 | 41 | "重复多次设置 DoubleBufferTask 的 Finish 方法,不会出现任何异常".Test(() => 42 | { 43 | var mock = new Mock(); 44 | mock.Setup(foo => foo.Foo()); 45 | var asyncManualResetEvent = new AsyncManualResetEvent(false); 46 | 47 | var doubleBufferTask = new DoubleBufferTask(async list => 48 | { 49 | await asyncManualResetEvent.WaitOneAsync(); 50 | 51 | foreach (var foo in list) 52 | { 53 | foo.Foo(); 54 | } 55 | }); 56 | doubleBufferTask.AddTask(mock.Object); 57 | 58 | var taskArray = new Task[100]; 59 | var manualResetEventSlim = new ManualResetEventSlim(false); 60 | 61 | const int n = 10; 62 | for (int i = 0; i < taskArray.Length; i++) 63 | { 64 | taskArray[i] = Task.Run(async () => 65 | { 66 | manualResetEventSlim.Wait(); 67 | for (int j = 0; j < n; j++) 68 | { 69 | await Task.Delay(TimeSpan.FromMilliseconds(50)); 70 | doubleBufferTask.Finish(); 71 | } 72 | }); 73 | } 74 | 75 | manualResetEventSlim.Set(); 76 | // 没有异常 77 | Task.WaitAll(taskArray); 78 | 79 | asyncManualResetEvent.Set(); 80 | doubleBufferTask.WaitAllTaskFinish().Wait(); 81 | }); 82 | } 83 | 84 | [ContractTestCase] 85 | public void DoAll() 86 | { 87 | "多线程加入任务,任务执行速度比加入快,可以等待所有任务执行完成".Test(() => 88 | { 89 | var mock = new Mock(); 90 | mock.Setup(foo => foo.Foo()); 91 | 92 | var doubleBufferTask = new DoubleBufferTask(list => 93 | { 94 | foreach (var foo in list) 95 | { 96 | foo.Foo(); 97 | } 98 | 99 | return Task.CompletedTask; 100 | }); 101 | 102 | const int n = 10; 103 | 104 | var taskArray = new Task[100]; 105 | 106 | for (int i = 0; i < taskArray.Length; i++) 107 | { 108 | taskArray[i] = Task.Run(async () => 109 | { 110 | for (int j = 0; j < n; j++) 111 | { 112 | await Task.Delay(TimeSpan.FromMilliseconds(50)); 113 | doubleBufferTask.AddTask(mock.Object); 114 | } 115 | }); 116 | } 117 | 118 | Task.WhenAll(taskArray).ContinueWith(_ => doubleBufferTask.Finish()); 119 | 120 | doubleBufferTask.WaitAllTaskFinish().Wait(); 121 | 122 | mock.Verify(foo => foo.Foo(), Times.Exactly(n * taskArray.Length)); 123 | }); 124 | 125 | "多线程加入任务,可以等待所有任务执行完成".Test(() => 126 | { 127 | var mock = new Mock(); 128 | mock.Setup(foo => foo.Foo()); 129 | 130 | var doubleBufferTask = new DoubleBufferTask(async list => 131 | { 132 | foreach (var foo in list) 133 | { 134 | await Task.Delay(TimeSpan.FromMilliseconds(10)); 135 | foo.Foo(); 136 | } 137 | }); 138 | 139 | const int n = 10; 140 | 141 | var taskArray = new Task[10]; 142 | 143 | for (int i = 0; i < taskArray.Length; i++) 144 | { 145 | taskArray[i] = Task.Run(async () => 146 | { 147 | for (int j = 0; j < n; j++) 148 | { 149 | await Task.Delay(TimeSpan.FromMilliseconds(50)); 150 | doubleBufferTask.AddTask(mock.Object); 151 | } 152 | }); 153 | } 154 | 155 | Task.WhenAll(taskArray).ContinueWith(_ => doubleBufferTask.Finish()); 156 | 157 | doubleBufferTask.WaitAllTaskFinish().Wait(); 158 | 159 | mock.Verify(foo => foo.Foo(), Times.Exactly(n * taskArray.Length)); 160 | }); 161 | 162 | "没有加入任务,等待完成,可以等待完成".Test(() => 163 | { 164 | var mock = new Mock(); 165 | mock.Setup(foo => foo.Foo()); 166 | 167 | var doubleBufferTask = new DoubleBufferTask(async list => 168 | { 169 | foreach (var foo in list) 170 | { 171 | await Task.Delay(TimeSpan.FromMilliseconds(50)); 172 | foo.Foo(); 173 | } 174 | }); 175 | 176 | doubleBufferTask.Finish(); 177 | 178 | doubleBufferTask.WaitAllTaskFinish().Wait(); 179 | 180 | // 没有执行一次 181 | mock.Verify(foo => foo.Foo(), Times.Never); 182 | }); 183 | } 184 | 185 | public interface IFoo 186 | { 187 | void Foo(); 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/DoubleBufferTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using dotnetCampus.Threading; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using Moq; 6 | using MSTest.Extensions.Contracts; 7 | 8 | namespace AsyncWorkerCollection.Tests 9 | { 10 | [TestClass] 11 | public class DoubleBufferTest 12 | { 13 | [ContractTestCase] 14 | public void DoAll() 15 | { 16 | "多线程随机延迟一边加入元素一边执行,可以执行所有元素".Test(() => 17 | { 18 | var mock = new Mock(); 19 | mock.Setup(foo => foo.Foo()); 20 | 21 | var random = new Random(); 22 | const int n = 100; 23 | 24 | var doubleBuffer = new DoubleBuffer(); 25 | 26 | var t1 = Task.Run(async () => 27 | { 28 | for (int i = 0; i < n; i++) 29 | { 30 | doubleBuffer.Add(mock.Object); 31 | await Task.Delay(random.Next(100)); 32 | } 33 | }); 34 | 35 | var t2 = Task.Run(async () => 36 | { 37 | await Task.Delay(300); 38 | await doubleBuffer.DoAllAsync(async list => 39 | { 40 | foreach (var foo in list) 41 | { 42 | await Task.Delay(random.Next(50)); 43 | foo.Foo(); 44 | } 45 | }); 46 | }); 47 | 48 | Task.WaitAll(t1, t2); 49 | 50 | doubleBuffer.DoAllAsync(async list => 51 | { 52 | foreach (var foo in list) 53 | { 54 | await Task.Delay(random.Next(50)); 55 | foo.Foo(); 56 | } 57 | }).Wait(); 58 | 59 | mock.Verify(foo => foo.Foo(), Times.Exactly(n)); 60 | }); 61 | 62 | "多线程一边加入元素一边执行,可以执行所有元素".Test(() => 63 | { 64 | var mock = new Mock(); 65 | mock.Setup(foo => foo.Foo()); 66 | 67 | const int n = 10000; 68 | 69 | var doubleBuffer = new DoubleBuffer(); 70 | 71 | for (int i = 0; i < n; i++) 72 | { 73 | doubleBuffer.Add(mock.Object); 74 | } 75 | 76 | var t1 = Task.Run(() => 77 | { 78 | for (int i = 0; i < n; i++) 79 | { 80 | doubleBuffer.Add(mock.Object); 81 | } 82 | }); 83 | 84 | var t2 = Task.Run(() => { doubleBuffer.DoAll(list => list.ForEach(foo => foo.Foo())); }); 85 | 86 | Task.WaitAll(t1, t2); 87 | 88 | // 没有执行一次 89 | mock.Verify(foo => foo.Foo(), Times.Exactly(n * 2)); 90 | }); 91 | 92 | "给定10次元素,执行 DoAll 元素执行10次".Test(() => 93 | { 94 | var mock = new Mock(); 95 | mock.Setup(foo => foo.Foo()); 96 | 97 | const int n = 10; 98 | 99 | var doubleBuffer = new DoubleBuffer(); 100 | 101 | for (int i = 0; i < n; i++) 102 | { 103 | doubleBuffer.Add(mock.Object); 104 | } 105 | 106 | doubleBuffer.DoAll(list => list.ForEach(foo => foo.Foo())); 107 | 108 | // 没有执行一次 109 | mock.Verify(foo => foo.Foo(), Times.Exactly(n)); 110 | }); 111 | 112 | "没有给定缓存内容,执行 DoAll 啥都不做".Test(() => 113 | { 114 | var mock = new Mock(); 115 | mock.Setup(foo => foo.Foo()); 116 | 117 | var doubleBuffer = new DoubleBuffer(); 118 | doubleBuffer.DoAll(list => list.ForEach(foo => foo.Foo())); 119 | 120 | // 没有执行一次 121 | mock.Verify(foo => foo.Foo(), Times.Never); 122 | }); 123 | } 124 | 125 | public interface IFoo 126 | { 127 | void Foo(); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /test/AsyncWorkerCollection.Tests/Reentrancy/QueueReentrancyTaskTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using dotnetCampus.Threading.Reentrancy; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using MSTest.Extensions.Contracts; 7 | 8 | namespace AsyncWorkerCollection.Tests.Reentrancy 9 | { 10 | [TestClass] 11 | public class QueueReentrancyTaskTests 12 | { 13 | [ContractTestCase] 14 | public void InvokeAsync() 15 | { 16 | "并发执行大量任务,最终返回值按顺序获取到。".Test(async () => 17 | { 18 | // Arrange 19 | var concurrentCount = 100; 20 | var resultList = new List(); 21 | var reentrancy = new QueueReentrancyTask(async i => 22 | { 23 | await Task.Delay(10).ConfigureAwait(false); 24 | resultList.Add(i); 25 | return i; 26 | }); 27 | 28 | // Action 29 | await Task.WhenAll(Enumerable.Range(0, concurrentCount).Select(i => reentrancy.InvokeAsync(i))); 30 | 31 | // Assert 32 | for (var i = 0; i < concurrentCount; i++) 33 | { 34 | Assert.AreEqual(i, resultList[i]); 35 | } 36 | }); 37 | } 38 | } 39 | } 40 | --------------------------------------------------------------------------------