├── ConcurrentPriorityQueue ├── Core │ ├── IHavePriority.cs │ ├── IPriorityQueue.cs │ ├── IConcurrentPriorityQueue.cs │ ├── ConcurrentPriorityQueueExtensions.cs │ └── ConcurrentPriorityQueue.cs ├── ConcurrentPriorityByIntegerQueue.cs └── ConcurrentPriorityQueue.csproj ├── ConcurrentPriorityQueueTests ├── MockWithIntegerPriority.cs ├── TestHelpers.cs ├── ConcurrentPriorityQueueTests.csproj ├── PriorityQueueBlockingCollectionUnitTests.cs ├── PriorityQueueIProducerConsumerUnitTests.cs ├── PriorityQueueIEnumerabeUnitTests.cs └── PriorityQueueUnitTests.cs ├── .github └── workflows │ ├── greetings.yml │ └── build.yml ├── GenericConcurrentPriorityQueueTests ├── MockWithObjectPriority.cs ├── TestHelpers.cs ├── TimeToProcess.cs ├── GenericConcurrentPriorityQueueTests.csproj ├── GenericPriorityQueueIEnumerabeUnitTests.cs ├── GenericPriorityQueueIProducerConsumerUnitTests.cs └── GenericPriorityQueueUnitTests.cs ├── Directory.Build.props ├── LICENSE ├── CONTRIBUTING.md ├── ConcurrentPriorityQueue.sln ├── .globalconfig ├── README.md └── .gitignore /ConcurrentPriorityQueue/Core/IHavePriority.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConcurrentPriorityQueue.Core 4 | { 5 | public interface IHavePriority 6 | where TP : IEquatable, IComparable 7 | { 8 | TP Priority { get; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue/Core/IPriorityQueue.cs: -------------------------------------------------------------------------------- 1 | using CSharpFunctionalExtensions; 2 | 3 | namespace ConcurrentPriorityQueue.Core 4 | { 5 | public interface IPriorityQueue 6 | { 7 | Result Enqueue(T item); 8 | 9 | Result Dequeue(); 10 | 11 | Result Peek(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue/Core/IConcurrentPriorityQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | 4 | namespace ConcurrentPriorityQueue.Core 5 | { 6 | public interface IConcurrentPriorityQueue : IProducerConsumerCollection, IPriorityQueue 7 | where T : IHavePriority 8 | where TP : IEquatable, IComparable 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/MockWithIntegerPriority.cs: -------------------------------------------------------------------------------- 1 | using ConcurrentPriorityQueue.Core; 2 | 3 | namespace ConcurrentPriorityQueueTests 4 | { 5 | public class MockWithIntegerPriority : IHavePriority 6 | { 7 | public MockWithIntegerPriority(int priority = 0) 8 | { 9 | Priority = priority; 10 | } 11 | 12 | public int Priority { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | with: 14 | repo-token: ${{ secrets.GITHUB_TOKEN }} 15 | issue-message: 'Hey there, freshman! Wassup?' 16 | pr-message: 'Hey bro! What’s sizzling?' -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/MockWithObjectPriority.cs: -------------------------------------------------------------------------------- 1 | using ConcurrentPriorityQueue.Core; 2 | 3 | namespace GenericConcurrentPriorityQueueTests 4 | { 5 | public class MockWithObjectPriority : IHavePriority 6 | { 7 | public MockWithObjectPriority(TimeToProcess timeToProcess) 8 | { 9 | Priority = timeToProcess; 10 | } 11 | 12 | public TimeToProcess Priority { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue/ConcurrentPriorityByIntegerQueue.cs: -------------------------------------------------------------------------------- 1 | using ConcurrentPriorityQueue.Core; 2 | 3 | namespace ConcurrentPriorityQueue 4 | { 5 | public class ConcurrentPriorityByIntegerQueue : ConcurrentPriorityQueue 6 | where T : IHavePriority 7 | { 8 | public ConcurrentPriorityByIntegerQueue() 9 | : base() { } 10 | 11 | public ConcurrentPriorityByIntegerQueue(int capacity) 12 | : base(capacity) { } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue/Core/ConcurrentPriorityQueueExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | 4 | namespace ConcurrentPriorityQueue.Core 5 | { 6 | public static class ConcurrentPriorityQueueExtensions 7 | { 8 | public static BlockingCollection ToBlockingCollection(this IConcurrentPriorityQueue queue) 9 | where T : IHavePriority 10 | where TP : IEquatable, IComparable => new BlockingCollection(queue); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/TestHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using ConcurrentPriorityQueue.Core; 4 | 5 | namespace ConcurrentPriorityQueueTests 6 | { 7 | public static class TestHelpers 8 | { 9 | public static IEnumerable MockItemsWithIntegerPriority => 10 | new List 11 | { 12 | new object[] { new MockWithIntegerPriority(0) }, 13 | new object[] { new MockWithIntegerPriority(1) }, 14 | new object[] { new MockWithIntegerPriority(2) }, 15 | }; 16 | 17 | public static List> GetItemsWithIntegerPriority() => 18 | MockItemsWithIntegerPriority 19 | .Select(objects => objects[0] as IHavePriority).ToList(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/TestHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using ConcurrentPriorityQueue.Core; 4 | 5 | namespace GenericConcurrentPriorityQueueTests 6 | { 7 | public static class TestHelpers 8 | { 9 | public static IEnumerable MockItemsWithObjectPriority => 10 | new List 11 | { 12 | new object[] { new MockWithObjectPriority(new TimeToProcess(0.25M)) }, 13 | new object[] { new MockWithObjectPriority(new TimeToProcess(0.5M)) }, 14 | new object[] { new MockWithObjectPriority(new TimeToProcess(1M)) }, 15 | }; 16 | 17 | public static List> GetItemsWithObjectPriority() => 18 | MockItemsWithObjectPriority 19 | .Select(objects => objects[0] as IHavePriority).ToList(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/TimeToProcess.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GenericConcurrentPriorityQueueTests 4 | { 5 | public class TimeToProcess : IEquatable, IComparable 6 | { 7 | public TimeToProcess(decimal timeToProcessInMilliseconds = 0) 8 | { 9 | TimeInMilliseconds = timeToProcessInMilliseconds; 10 | } 11 | 12 | public decimal TimeInMilliseconds { get; } 13 | 14 | public int CompareTo(TimeToProcess other) => 15 | TimeInMilliseconds.CompareTo(other.TimeInMilliseconds); 16 | 17 | public bool Equals(TimeToProcess other) => 18 | TimeInMilliseconds.Equals(other.TimeInMilliseconds); 19 | 20 | public override int GetHashCode() => TimeInMilliseconds.GetHashCode(); 21 | 22 | public override bool Equals(object obj) => obj is TimeToProcess process && Equals(process); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test ConcurrentPriorityQueue 2 | 3 | on: 4 | push: 5 | branches: [develop] 6 | pull_request: 7 | branches: [develop] 8 | 9 | concurrency: 10 | group: ${{github.workflow}}-${{github.event.pull_request.number || github.ref}} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | build: 15 | runs-on: windows-latest 16 | 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v4.1.1 20 | with: 21 | fetch-depth: 0 22 | 23 | - name: Setup .NET 24 | uses: actions/setup-dotnet@v4.0.0 25 | with: 26 | dotnet-version: | 27 | 8.x 28 | 6.x 29 | 2.x 30 | 31 | - name: Restore dependencies 32 | run: dotnet restore 33 | 34 | - name: Build 35 | run: dotnet build --no-restore 36 | 37 | - name: Test 38 | run: dotnet test --no-build --verbosity normal 39 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | all 5 | runtime; build; native; contentfiles; analyzers; buildtransitive 6 | 7 | 8 | all 9 | runtime; build; native; contentfiles; analyzers; buildtransitive 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 3.0.0 18 | 19 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue/ConcurrentPriorityQueue.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | true 5 | net48;netstandard2.0;net6.0;net8.0 6 | Noam Yogev 7 | A thread-safe generic first in-first out (FIFO) collection with support for priority queuing. 8 | https://github.com/noamyogev84/ConcurrentPriorityQueue 9 | https://github.com/noamyogev84/ConcurrentPriorityQueue 10 | threading thread-safe producerconsumer concurrent-collection concurrent blocking-collection collections 11 | ConcurrentPriorityQueue 12 | 3.0.0 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/GenericConcurrentPriorityQueueTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net48;net6.0;net8.0 5 | false 6 | true 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Noam Yogev 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 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/ConcurrentPriorityQueueTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net48;net6.0;net8.0 5 | ..\ConcurrentPriorityQueue.ruleset 6 | false 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | all 26 | runtime; build; native; contentfiles; analyzers; buildtransitive 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to ConcurrentPriorityQueue 2 | 3 | :+1::tada: First off, thanks for taking the time to contribute! :tada::+1: 4 | 5 | This quick contributing guide will get you up and running in no time! :crown::+1: 6 | Simply follow the below steps and get yourslef cofortable with the code. 7 | 8 | We welcome any kinds of contributions. From new features (PR's) to bugs and documentation. All are welcomed! :tada::+1: 9 | 10 | ## What should I know before I get started? 11 | 12 | ### .NET Development 13 | 14 | Download and install the .NET SDK from the official .NET website. 15 | The quickest and easiest way to build and debug this project is with using Visual Studio Code. 16 | 17 | - [Get Dotnet SDK](https://dotnet.microsoft.com/en-us/download) 18 | - [Get Visual Studio Code](https://code.visualstudio.com/download) 19 | - [Get C# Dev Kit for VSCode](https://code.visualstudio.com/docs/languages/dotnet) 20 | 21 | ### Cloning ConcurrentPriorityQueue 22 | 23 | ``` 24 | git clone https://github.com/noamyogev84/ConcurrentPriorityQueue.git && cd ConcurrentPriorityQueue 25 | ``` 26 | 27 | ### Building ConcurrentPriorityQueue 28 | 29 | ``` 30 | C:\Some_Folder\ConcurrentPriorityQueue>dotnet build 31 | ``` 32 | ### Testing ConcurrentPriorityQueue 33 | 34 | ``` 35 | C:\Some_Folder\ConcurrentPriorityQueue>dotnet test 36 | ``` 37 | 38 | ## What should I know before I get started? 39 | 40 | Contributing to this repository is done by openening PRs or new issues. 41 | For PR's, we encourage you to fork this repository first, and only then open a new PR. 42 | 43 | [Fork a repository](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) 44 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34408.163 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConcurrentPriorityQueue", "ConcurrentPriorityQueue\ConcurrentPriorityQueue.csproj", "{E6C7464F-9840-4477-AB3E-8D7A4539D016}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConcurrentPriorityQueueTests", "ConcurrentPriorityQueueTests\ConcurrentPriorityQueueTests.csproj", "{E457395E-76DD-45D4-A898-C6D299ACF7AD}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GenericConcurrentPriorityQueueTests", "GenericConcurrentPriorityQueueTests\GenericConcurrentPriorityQueueTests.csproj", "{D5BAFA8A-1330-468A-B183-451C5349F198}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {E6C7464F-9840-4477-AB3E-8D7A4539D016}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {E6C7464F-9840-4477-AB3E-8D7A4539D016}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {E6C7464F-9840-4477-AB3E-8D7A4539D016}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {E6C7464F-9840-4477-AB3E-8D7A4539D016}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {E457395E-76DD-45D4-A898-C6D299ACF7AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {E457395E-76DD-45D4-A898-C6D299ACF7AD}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {E457395E-76DD-45D4-A898-C6D299ACF7AD}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {E457395E-76DD-45D4-A898-C6D299ACF7AD}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {D5BAFA8A-1330-468A-B183-451C5349F198}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {D5BAFA8A-1330-468A-B183-451C5349F198}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {D5BAFA8A-1330-468A-B183-451C5349F198}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {D5BAFA8A-1330-468A-B183-451C5349F198}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {7613249C-4B66-44BD-ADF7-F77E182034DE} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/PriorityQueueBlockingCollectionUnitTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Threading.Tasks; 4 | using ConcurrentPriorityQueue; 5 | using ConcurrentPriorityQueue.Core; 6 | using FluentAssertions; 7 | using Xunit; 8 | 9 | namespace ConcurrentPriorityQueueTests 10 | { 11 | /// 12 | /// Test Blocking collection functionality. 13 | /// 14 | public class PriorityQueueBlockingCollectionUnitTests : IDisposable 15 | { 16 | private readonly BlockingCollection> _targetCollection; 17 | 18 | public PriorityQueueBlockingCollectionUnitTests() 19 | { 20 | _targetCollection = new ConcurrentPriorityByIntegerQueue>() 21 | .ToBlockingCollection(); 22 | } 23 | 24 | [Fact] 25 | public async Task Test_ConsumingTaskBlocksUntilNoMoreAdditionsAsync() 26 | { 27 | const int numberOfItemsToAdd = 10; 28 | const int defaultSleepTimeBetweenAdds = 1000; 29 | 30 | // Add items and signal for completion when done. 31 | _ = Task.Run(() => AddItemsAsync(numberOfItemsToAdd, defaultSleepTimeBetweenAdds)) 32 | .ContinueWith(t => _targetCollection.CompleteAdding()); 33 | 34 | // Take items as long as they continue to be added. 35 | _ = Task.Run(TakeItemsAsync).ConfigureAwait(true); 36 | 37 | // Wait for all tasks to end. 38 | await Task.WhenAll(AddItemsAsync(numberOfItemsToAdd, defaultSleepTimeBetweenAdds), TakeItemsAsync()).ConfigureAwait(true); 39 | } 40 | 41 | public void Dispose() => _targetCollection.Dispose(); 42 | 43 | private async Task AddItemsAsync(int numberOfItemsToAdd, int sleepTime = 0) 44 | { 45 | for (var i = 0; i < numberOfItemsToAdd; ++i) 46 | { 47 | _targetCollection.Add(new MockWithIntegerPriority()); 48 | await Task.Delay(sleepTime).ConfigureAwait(false); 49 | } 50 | } 51 | 52 | private Task TakeItemsAsync() 53 | { 54 | // blocks until signaled on completion. 55 | foreach (var item in _targetCollection.GetConsumingEnumerable()) 56 | { 57 | item.Should().BeOfType(); 58 | } 59 | 60 | return Task.CompletedTask; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/GenericPriorityQueueIEnumerabeUnitTests.cs: -------------------------------------------------------------------------------- 1 | using ConcurrentPriorityQueue.Core; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace GenericConcurrentPriorityQueueTests 6 | { 7 | /// 8 | /// Test IEnumerable functionality. 9 | /// 10 | public class GenericPriorityQueueIEnumerabeUnitTests 11 | { 12 | private readonly IConcurrentPriorityQueue, TimeToProcess> _targetQueue; 13 | 14 | public GenericPriorityQueueIEnumerabeUnitTests() 15 | { 16 | _targetQueue = new ConcurrentPriorityQueue, TimeToProcess>(); 17 | } 18 | 19 | [Fact] 20 | public void GetEnumerator_QueueContainsDifferentPriorities_EnumerationIsOrderedByPriority() 21 | { 22 | // Arrange 23 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 24 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 25 | 26 | // Assert 27 | var index = 0; 28 | foreach (var item in _targetQueue) 29 | { 30 | item.Priority.Should().Be(mockItems[index++].Priority); 31 | } 32 | } 33 | 34 | [Fact] 35 | public void GetEnumerator_QueueContainsSamePriorities_EnumerationIsOrderedByFirstIn() 36 | { 37 | // Arrange 38 | var mockWithPriority1 = new MockWithObjectPriority(new TimeToProcess(0.25M)); 39 | var mockWithPriority2 = new MockWithObjectPriority(new TimeToProcess(0.25M)); 40 | 41 | _targetQueue.Enqueue(mockWithPriority1); 42 | _targetQueue.Enqueue(mockWithPriority2); 43 | 44 | // Act 45 | var enumerator = _targetQueue.GetEnumerator(); 46 | 47 | // Assert 48 | enumerator.MoveNext(); 49 | enumerator.Current.Should().Be(mockWithPriority1); 50 | enumerator.MoveNext(); 51 | enumerator.Current.Should().Be(mockWithPriority2); 52 | } 53 | 54 | [Fact] 55 | public void Count_ReturnsAggregatedCount() 56 | { 57 | // Arrange 58 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 59 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 60 | 61 | // Act 62 | var totalCount = _targetQueue.Count; 63 | 64 | // Assert 65 | totalCount.Should().Be(mockItems.Count); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/PriorityQueueIProducerConsumerUnitTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConcurrentPriorityQueue; 3 | using ConcurrentPriorityQueue.Core; 4 | using FluentAssertions; 5 | using Xunit; 6 | 7 | namespace ConcurrentPriorityQueueTests 8 | { 9 | public class PriorityQueueIProducerConsumerUnitTests 10 | { 11 | private readonly IConcurrentPriorityQueue, int> _targetQueue; 12 | 13 | public PriorityQueueIProducerConsumerUnitTests() 14 | { 15 | _targetQueue = new ConcurrentPriorityByIntegerQueue>(); 16 | } 17 | 18 | [Fact] 19 | public void ToArray_QueueContainsElements_ReturnsItemsArray() 20 | { 21 | // Arrange 22 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 23 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 24 | 25 | // Arrange 26 | var result = _targetQueue.ToArray(); 27 | 28 | // Assert 29 | result.Length.Should().Be(mockItems.Count); 30 | result.Should().BeEquivalentTo(mockItems.ToArray()); 31 | } 32 | 33 | [Fact] 34 | public void ToArray_QueueContainsNoElements_ReturnsEmptyArray() 35 | { 36 | // Arrange 37 | var result = _targetQueue.ToArray(); 38 | 39 | // Assert 40 | result.Should().BeEmpty(); 41 | } 42 | 43 | [Fact] 44 | public void CopyTo_GetsArray_CopiesAllItems() 45 | { 46 | // Arrange 47 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 48 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 49 | var newArray = new IHavePriority[3]; 50 | 51 | // Act 52 | _targetQueue.CopyTo(newArray, 0); 53 | 54 | // Assert 55 | newArray.Length.Should().Be(mockItems.Count); 56 | newArray.Should().BeEquivalentTo(mockItems.ToArray()); 57 | } 58 | 59 | [Fact] 60 | public void CopyTo_GetsArrayType_CopiesAllItems() 61 | { 62 | // Arrange 63 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 64 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 65 | var newArray = Array.CreateInstance(typeof(IHavePriority), mockItems.Count); 66 | 67 | // Act 68 | _targetQueue.CopyTo(newArray, 0); 69 | 70 | // Assert 71 | newArray.Length.Should().Be(mockItems.Count); 72 | newArray.Should().BeEquivalentTo(mockItems.ToArray()); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/GenericPriorityQueueIProducerConsumerUnitTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConcurrentPriorityQueue.Core; 3 | using FluentAssertions; 4 | using Xunit; 5 | 6 | namespace GenericConcurrentPriorityQueueTests 7 | { 8 | public class GenericPriorityQueueIProducerConsumerUnitTests 9 | { 10 | private readonly IConcurrentPriorityQueue, TimeToProcess> _targetQueue; 11 | 12 | public GenericPriorityQueueIProducerConsumerUnitTests() 13 | { 14 | _targetQueue = new ConcurrentPriorityQueue, TimeToProcess>(); 15 | } 16 | 17 | [Fact] 18 | public void ToArray_QueueContainsElements_ReturnsItemsArray() 19 | { 20 | // Arrange 21 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 22 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 23 | 24 | // Arrange 25 | var result = _targetQueue.ToArray(); 26 | 27 | // Assert 28 | result.Length.Should().Be(mockItems.Count); 29 | result.Should().BeEquivalentTo(mockItems.ToArray()); 30 | } 31 | 32 | [Fact] 33 | public void ToArray_QueueContainsNoElements_ReturnsEmptyArray() 34 | { 35 | // Arrange 36 | var result = _targetQueue.ToArray(); 37 | 38 | // Assert 39 | result.Should().BeEmpty(); 40 | } 41 | 42 | [Fact] 43 | public void CopyTo_GetsArray_CopiesAllItems() 44 | { 45 | // Arrange 46 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 47 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 48 | var newArray = new IHavePriority[3]; 49 | 50 | // Act 51 | _targetQueue.CopyTo(newArray, 0); 52 | 53 | // Assert 54 | newArray.Length.Should().Be(mockItems.Count); 55 | newArray.Should().BeEquivalentTo(mockItems.ToArray()); 56 | } 57 | 58 | [Fact] 59 | public void CopyTo_GetsArrayType_CopiesAllItems() 60 | { 61 | // Arrange 62 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 63 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 64 | var newArray = Array.CreateInstance(typeof(IHavePriority), mockItems.Count); 65 | 66 | // Act 67 | _targetQueue.CopyTo(newArray, 0); 68 | 69 | // Assert 70 | newArray.Length.Should().Be(mockItems.Count); 71 | newArray.Should().BeEquivalentTo(mockItems.ToArray()); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/PriorityQueueIEnumerabeUnitTests.cs: -------------------------------------------------------------------------------- 1 | using ConcurrentPriorityQueue; 2 | using ConcurrentPriorityQueue.Core; 3 | using FluentAssertions; 4 | using Xunit; 5 | 6 | namespace ConcurrentPriorityQueueTests 7 | { 8 | /// 9 | /// Test IEnumerable functionality. 10 | /// 11 | public class PriorityQueueIEnumerabeUnitTests 12 | { 13 | private readonly IConcurrentPriorityQueue, int> _targetQueue; 14 | 15 | public PriorityQueueIEnumerabeUnitTests() 16 | { 17 | _targetQueue = new ConcurrentPriorityByIntegerQueue>(); 18 | } 19 | 20 | [Fact] 21 | public void GetEnumerator_QueueContainsDifferentPriorities_EnumerationIsOrderedByPriority() 22 | { 23 | // Arrange 24 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 25 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 26 | 27 | // Assert 28 | var expectedPriority = 0; 29 | foreach (var item in _targetQueue) 30 | { 31 | item.Priority.Should().Be(expectedPriority++); 32 | } 33 | } 34 | 35 | [Fact] 36 | public void GetEnumerator_QueueContainsSamePriorities_EnumerationIsOrderedByFirstIn() 37 | { 38 | // Arrange 39 | var mockWithPriority1 = new MockWithIntegerPriority(0); 40 | var mockWithPriority2 = new MockWithIntegerPriority(0); 41 | 42 | _targetQueue.Enqueue(mockWithPriority1); 43 | _targetQueue.Enqueue(mockWithPriority2); 44 | 45 | // Act 46 | var enumerator = _targetQueue.GetEnumerator(); 47 | 48 | // Assert 49 | enumerator.MoveNext(); 50 | enumerator.Current.Should().Be(mockWithPriority1); 51 | enumerator.MoveNext(); 52 | enumerator.Current.Should().Be(mockWithPriority2); 53 | } 54 | 55 | [Fact] 56 | public void Count_QueueContainsItems_ReturnsAggregatedCount() 57 | { 58 | // Arrange 59 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 60 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 61 | 62 | // Act 63 | var totalCount = _targetQueue.Count; 64 | 65 | // Assert 66 | totalCount.Should().Be(mockItems.Count); 67 | } 68 | 69 | [Fact] 70 | public void Count_QueueIsEmpty_ReturnsZero() 71 | { 72 | // Act 73 | var totalCount = _targetQueue.Count; 74 | 75 | // Assert 76 | totalCount.Should().Be(0); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /.globalconfig: -------------------------------------------------------------------------------- 1 | is_global = true 2 | 3 | indent_size = 4 4 | indent_style = space 5 | 6 | # SA1027: Use tabs correctly 7 | dotnet_diagnostic.SA1027.severity = none 8 | 9 | # SA1600: Elements should be documented 10 | dotnet_diagnostic.SA1600.severity = suggestion 11 | 12 | # SA1502: Element should not be on a single line 13 | dotnet_diagnostic.SA1502.severity = none 14 | 15 | # SA1633: File should have header 16 | dotnet_diagnostic.SA1633.severity = none 17 | 18 | # SA1200: Using directives should be placed correctly 19 | dotnet_diagnostic.SA1200.severity = none 20 | 21 | # SA1309: Field names should not begin with underscore 22 | dotnet_diagnostic.SA1309.severity = none 23 | 24 | # SA1101: Prefix local calls with this 25 | dotnet_diagnostic.SA1101.severity = none 26 | 27 | # IDE0011: Add braces 28 | csharp_prefer_braces = when_multiline 29 | 30 | # IDE0008: Use explicit type 31 | csharp_style_var_elsewhere = false 32 | 33 | # IDE0008: Use explicit type 34 | dotnet_diagnostic.IDE0008.severity = suggestion 35 | 36 | # CA1711: Identifiers should not have incorrect suffix 37 | dotnet_diagnostic.CA1711.severity = none 38 | 39 | # CA1010: Generic interface should also be implemented 40 | dotnet_diagnostic.CA1010.severity = suggestion 41 | 42 | # SA1503: Braces should not be omitted 43 | dotnet_diagnostic.SA1503.severity = none 44 | 45 | # IDE0022: Use block body for methods 46 | csharp_style_expression_bodied_methods = when_on_single_line 47 | 48 | # IDE0058: Expression value is never used 49 | csharp_style_unused_value_expression_statement_preference = unused_local_variable 50 | 51 | # IDE0058: Expression value is never used 52 | dotnet_diagnostic.IDE0058.severity = suggestion 53 | 54 | # SA1501: Statement should not be on a single line 55 | dotnet_diagnostic.SA1501.severity = suggestion 56 | 57 | # SA0001: XML analysis is disabled 58 | dotnet_diagnostic.SA0001.severity = none 59 | 60 | # IDE0090: Use 'new(...)' 61 | dotnet_diagnostic.IDE0090.severity = suggestion 62 | 63 | # IDE0130: Namespace does not match folder structure 64 | dotnet_style_namespace_match_folder = false 65 | 66 | # IDE0130: Namespace does not match folder structure 67 | dotnet_diagnostic.IDE0130.severity = suggestion 68 | 69 | # CA1707: Identifiers should not contain underscores 70 | dotnet_diagnostic.CA1707.severity = suggestion 71 | 72 | # CA1816: Dispose methods should call SuppressFinalize 73 | dotnet_diagnostic.CA1816.severity = suggestion 74 | 75 | # CA1067: Override Object.Equals(object) when implementing IEquatable 76 | dotnet_diagnostic.CA1067.severity = suggestion 77 | 78 | # CA1036: Override methods on comparable types 79 | dotnet_diagnostic.CA1036.severity = suggestion 80 | 81 | # CA1036: Override methods on comparable types 82 | dotnet_diagnostic.VSTHRD200.severity = suggestion 83 | 84 | # VSTHRD105: Avoid method overloads that assume TaskScheduler.Current 85 | dotnet_diagnostic.VSTHRD105.severity = suggestion 86 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueue/Core/ConcurrentPriorityQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using CSharpFunctionalExtensions; 6 | 7 | namespace ConcurrentPriorityQueue.Core 8 | { 9 | public class ConcurrentPriorityQueue : IConcurrentPriorityQueue 10 | where T : IHavePriority 11 | where TP : IEquatable, IComparable 12 | { 13 | private readonly Dictionary> _internalQueues; 14 | private readonly int _capacity; 15 | 16 | public ConcurrentPriorityQueue(int capacity = 0) 17 | { 18 | _internalQueues = new Dictionary>(); 19 | _capacity = capacity; 20 | } 21 | 22 | public int Count => _internalQueues.Values.Sum((q) => q.Count); 23 | 24 | public bool IsSynchronized => true; 25 | 26 | public object SyncRoot { get; } = new object(); 27 | 28 | public void CopyTo(T[] array, int index) => ToArray().CopyTo(array, index); 29 | 30 | public void CopyTo(Array array, int index) => CopyTo((T[])array, index); 31 | 32 | public T[] ToArray() 33 | { 34 | lock (SyncRoot) 35 | { 36 | return _internalQueues.OrderBy((q) => q.Key).SelectMany((q) => q.Value).ToArray(); 37 | } 38 | } 39 | 40 | public bool TryAdd(T item) => Enqueue(item).IsSuccess; 41 | 42 | public bool TryTake(out T item) 43 | { 44 | var result = Dequeue(); 45 | 46 | if (result.IsFailure) 47 | { 48 | item = default; 49 | return false; 50 | } 51 | else 52 | { 53 | item = result.Value; 54 | return true; 55 | } 56 | } 57 | 58 | public IEnumerator GetEnumerator() => ((IEnumerable)ToArray()).GetEnumerator(); 59 | 60 | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); 61 | 62 | public Result Enqueue(T item) 63 | { 64 | lock (SyncRoot) 65 | { 66 | return AddOrUpdate(item); 67 | } 68 | } 69 | 70 | public Result Dequeue() 71 | { 72 | lock (SyncRoot) 73 | { 74 | return GetNextQueue() 75 | .Map(q => q.Dequeue()) 76 | .TapError(err => Result.Failure(err)); 77 | } 78 | } 79 | 80 | public Result Peek() 81 | { 82 | lock (SyncRoot) 83 | { 84 | return GetNextQueue() 85 | .Map(q => q.Peek()) 86 | .TapError(err => Result.Failure(err)); 87 | } 88 | } 89 | 90 | private Result> GetNextQueue() 91 | { 92 | return _internalQueues.OrderBy((q) => q.Key).Select((q) => q.Value).FirstOrDefault((q) => q.Count > 0) is Queue queue 93 | ? Result.Success(queue) 94 | : Result.Failure>("Could not find a queue with items."); 95 | } 96 | 97 | private Result AddOrUpdate(T item) 98 | { 99 | if (_internalQueues.TryGetValue(item.Priority, out Queue queue)) 100 | { 101 | queue.Enqueue(item); 102 | return Result.Success(); 103 | } 104 | else if (!IsAtMaxCapacity()) 105 | { 106 | Queue newQueue = new Queue(); 107 | newQueue.Enqueue(item); 108 | _internalQueues.Add(item.Priority, newQueue); 109 | return Result.Success(); 110 | } 111 | else 112 | { 113 | return Result.Failure("Reached max capacity."); 114 | } 115 | } 116 | 117 | private bool IsAtMaxCapacity() => _capacity != 0 && Count == _capacity; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /GenericConcurrentPriorityQueueTests/GenericPriorityQueueUnitTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using ConcurrentPriorityQueue.Core; 3 | using FluentAssertions; 4 | using Xunit; 5 | 6 | namespace GenericConcurrentPriorityQueueTests 7 | { 8 | /// 9 | /// Test general functionalty of the queue [Enqueue, Dequeue, Peek]. 10 | /// 11 | public class GenericPriorityQueueUnitTests 12 | { 13 | private readonly IPriorityQueue> _targetQueue; 14 | 15 | public GenericPriorityQueueUnitTests() 16 | { 17 | var maxCapacity = 3; 18 | _targetQueue = new ConcurrentPriorityQueue, TimeToProcess>(maxCapacity); 19 | } 20 | 21 | [Fact] 22 | public void Enqueue_GetsValidPriorityItem_ReturnsSuccess() 23 | { 24 | // Assert 25 | TestHelpers.GetItemsWithObjectPriority().ForEach(i => 26 | { 27 | var result = _targetQueue.Enqueue(i); 28 | result.IsSuccess.Should().BeTrue(); 29 | }); 30 | } 31 | 32 | [Fact] 33 | public void Enqueue_MaxCapacityReached_TryToEnqueueNewPriority_Failes() 34 | { 35 | // Arrange 36 | TestHelpers.GetItemsWithObjectPriority().ForEach(i => _targetQueue.Enqueue(i)); 37 | 38 | var mockWithPriority = new MockWithObjectPriority(new TimeToProcess(1.5M)); 39 | 40 | // Act 41 | var result = _targetQueue.Enqueue(mockWithPriority); 42 | 43 | // Assert 44 | result.IsFailure.Should().BeTrue(); 45 | } 46 | 47 | [Fact] 48 | public void Enqueue_MaxCapacityReached_TryToEnqueueExistingPriority_Succeedes() 49 | { 50 | // Arrange 51 | TestHelpers.GetItemsWithObjectPriority().ForEach(i => _targetQueue.Enqueue(i)); 52 | var mockWithPriority = TestHelpers.GetItemsWithObjectPriority().First(); 53 | 54 | // Act 55 | var result = _targetQueue.Enqueue(mockWithPriority); 56 | 57 | // Assert 58 | result.IsSuccess.Should().BeTrue(); 59 | } 60 | 61 | [Fact] 62 | public void Dequeue_ReturnsSuccessResultWithTopPriorityItem() 63 | { 64 | // Arrange 65 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 66 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 67 | 68 | // Act 69 | var result1 = _targetQueue.Dequeue(); 70 | var result2 = _targetQueue.Dequeue(); 71 | var result3 = _targetQueue.Dequeue(); 72 | 73 | // Assert 74 | result1.Value.Priority.Should().Be(new TimeToProcess(0.25M)); 75 | result2.Value.Priority.Should().Be(new TimeToProcess(0.5M)); 76 | result3.Value.Priority.Should().Be(new TimeToProcess(1M)); 77 | } 78 | 79 | [Fact] 80 | public void Dequeue_QueueIsEmptyReturnsFailureResult() 81 | { 82 | // Act 83 | var result = _targetQueue.Dequeue(); 84 | 85 | // Assert 86 | result.IsFailure.Should().BeTrue(); 87 | } 88 | 89 | [Fact] 90 | public void Dequeue_QueueContainsItemsWithSamePriority_ReturnsSuccessWithFirstInItem() 91 | { 92 | // Arrange 93 | var mockWithPriority1 = new MockWithObjectPriority(new TimeToProcess(0.5M)); 94 | var mockWithPriority2 = new MockWithObjectPriority(new TimeToProcess(0.5M)); 95 | _targetQueue.Enqueue(mockWithPriority1); 96 | _targetQueue.Enqueue(mockWithPriority2); 97 | 98 | // Act 99 | var result1 = _targetQueue.Dequeue(); 100 | var result2 = _targetQueue.Dequeue(); 101 | 102 | // Assert 103 | result1.Value.Should().Be(mockWithPriority1); 104 | result2.Value.Should().Be(mockWithPriority2); 105 | } 106 | 107 | [Fact] 108 | public void Peek_ReturnsSuccessResultWithTopPriorityItem() 109 | { 110 | // Arrange 111 | var mockItems = TestHelpers.GetItemsWithObjectPriority(); 112 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 113 | 114 | // Act 115 | var result = _targetQueue.Peek(); 116 | 117 | // Assert 118 | result.Value.Priority.Should().Be(new TimeToProcess(0.25M)); 119 | } 120 | 121 | [Fact] 122 | public void Peek_QueueContainsItemsWithSamePriority_ReturnsSuccessWithFirstInItem() 123 | { 124 | // Arrange 125 | var mockWithPriority1 = new MockWithObjectPriority(new TimeToProcess(0.5M)); 126 | var mockWithPriority2 = new MockWithObjectPriority(new TimeToProcess(0.5M)); 127 | _targetQueue.Enqueue(mockWithPriority1); 128 | _targetQueue.Enqueue(mockWithPriority2); 129 | 130 | // Act 131 | var result1 = _targetQueue.Dequeue(); 132 | var result2 = _targetQueue.Dequeue(); 133 | 134 | // Assert 135 | result1.Value.Should().Be(mockWithPriority1); 136 | result2.Value.Should().Be(mockWithPriority2); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /ConcurrentPriorityQueueTests/PriorityQueueUnitTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using ConcurrentPriorityQueue; 3 | using ConcurrentPriorityQueue.Core; 4 | using FluentAssertions; 5 | using Xunit; 6 | 7 | namespace ConcurrentPriorityQueueTests 8 | { 9 | /// 10 | /// Test general functionalty of the queue [Enqueue, Dequeue, Peek]. 11 | /// 12 | public class PriorityQueueUnitTests 13 | { 14 | private readonly IPriorityQueue> _targetQueue; 15 | 16 | public PriorityQueueUnitTests() 17 | { 18 | var maxCapacity = 3; 19 | _targetQueue = new ConcurrentPriorityByIntegerQueue>(maxCapacity); 20 | } 21 | 22 | [Fact] 23 | public void Enqueue_GetsValidPriorityItem_ReturnsSuccess() 24 | { 25 | // Assert 26 | TestHelpers.GetItemsWithIntegerPriority().ForEach(i => 27 | { 28 | var result = _targetQueue.Enqueue(i); 29 | result.IsSuccess.Should().BeTrue(); 30 | }); 31 | } 32 | 33 | [Fact] 34 | public void Enqueue_MaxCapacityReached_TryToEnqueueNewPriority_Failes() 35 | { 36 | // Arrange 37 | TestHelpers.GetItemsWithIntegerPriority().ForEach(i => _targetQueue.Enqueue(i)); 38 | 39 | var mockWithPriority = new MockWithIntegerPriority(10); 40 | 41 | // Act 42 | var result = _targetQueue.Enqueue(mockWithPriority); 43 | 44 | // Assert 45 | result.IsFailure.Should().BeTrue(); 46 | } 47 | 48 | [Fact] 49 | public void Enqueue_MaxCapacityReached_TryToEnqueueExistingPriority_Succeedes() 50 | { 51 | // Arrange 52 | TestHelpers.GetItemsWithIntegerPriority().ForEach(i => _targetQueue.Enqueue(i)); 53 | var mockWithPriority = TestHelpers.GetItemsWithIntegerPriority().First(); 54 | 55 | // Act 56 | var result = _targetQueue.Enqueue(mockWithPriority); 57 | 58 | // Assert 59 | result.IsSuccess.Should().BeTrue(); 60 | } 61 | 62 | [Fact] 63 | public void Dequeue_ReturnsSuccessResultWithTopPriorityItem() 64 | { 65 | // Arrange 66 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 67 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 68 | 69 | // Act 70 | var result1 = _targetQueue.Dequeue(); 71 | var result2 = _targetQueue.Dequeue(); 72 | var result3 = _targetQueue.Dequeue(); 73 | 74 | // Assert 75 | result1.Value.Priority.Should().Be(0); 76 | result2.Value.Priority.Should().Be(1); 77 | result3.Value.Priority.Should().Be(2); 78 | } 79 | 80 | [Fact] 81 | public void Dequeue_QueueIsEmptyReturnsFailureResult() 82 | { 83 | // Act 84 | var result = _targetQueue.Dequeue(); 85 | 86 | // Assert 87 | result.IsFailure.Should().BeTrue(); 88 | } 89 | 90 | [Fact] 91 | public void Dequeue_QueueContainsItemsWithSamePriority_ReturnsSuccessWithFirstInItem() 92 | { 93 | // Arrange 94 | var mockWithPriority1 = new MockWithIntegerPriority(0); 95 | var mockWithPriority2 = new MockWithIntegerPriority(0); 96 | _targetQueue.Enqueue(mockWithPriority1); 97 | _targetQueue.Enqueue(mockWithPriority2); 98 | 99 | // Act 100 | var result1 = _targetQueue.Dequeue(); 101 | var result2 = _targetQueue.Dequeue(); 102 | 103 | // Assert 104 | result1.Value.Should().Be(mockWithPriority1); 105 | result2.Value.Should().Be(mockWithPriority2); 106 | } 107 | 108 | [Fact] 109 | public void Peek_ReturnsSuccessResultWithTopPriorityItem() 110 | { 111 | // Arrange 112 | var mockItems = TestHelpers.GetItemsWithIntegerPriority(); 113 | mockItems.ForEach(i => _targetQueue.Enqueue(i)); 114 | 115 | // Act 116 | var result = _targetQueue.Peek(); 117 | 118 | // Assert 119 | result.Value.Priority.Should().Be(0); 120 | } 121 | 122 | [Fact] 123 | public void Peek_QueueIsEmptyReturnsFailureResult() 124 | { 125 | // Act 126 | var result = _targetQueue.Peek(); 127 | 128 | // Assert 129 | result.IsFailure.Should().BeTrue(); 130 | } 131 | 132 | [Fact] 133 | public void Peek_QueueContainsItemsWithSamePriority_ReturnsSuccessWithFirstInItem() 134 | { 135 | // Arrange 136 | var mockWithPriority1 = new MockWithIntegerPriority(0); 137 | var mockWithPriority2 = new MockWithIntegerPriority(0); 138 | _targetQueue.Enqueue(mockWithPriority1); 139 | _targetQueue.Enqueue(mockWithPriority2); 140 | 141 | // Act 142 | var result1 = _targetQueue.Dequeue(); 143 | var result2 = _targetQueue.Dequeue(); 144 | 145 | // Assert 146 | result1.Value.Should().Be(mockWithPriority1); 147 | result2.Value.Should().Be(mockWithPriority2); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ConcurrentPriorityQueue ![Build Workflow](https://github.com/noamyogev84/ConcurrentPriorityQueue/actions/workflows/build.yml/badge.svg) ![Nuget](https://img.shields.io/nuget/v/ConcurrentPriorityQueue) 2 | 3 | A thread-safe generic first in first out (FIFO) collection with support for priority queuing. 4 | 5 | Nuget: [https://www.nuget.org/packages/ConcurrentPriorityQueue](https://www.nuget.org/packages/ConcurrentPriorityQueue) 6 | 7 | ### Features 8 | 9 | 1. Thread-Safe. 10 | 2. Manages items according to a `First in first out` policy and `priority` on top of that. 11 | 3. Implements `IProducerConsumerCollection` interface. 12 | 4. Extends to a `BlockingCollection`. 13 | 5. Supports multi-frameworks, includes `net48` `netstandard2.0` `net6.0` `net8.0` 14 | 15 | ### Examples: 16 | 17 | Items in the collection **must** implement the generic interface `IHavePriority` where T: implements `IEquatable`, `IComparable` and also overrides `Object.GetHashCode()`: 18 | 19 | ```csharp 20 | // Simplest implementation of IHavePriority 21 | public class SomeClass : IHavePriority { 22 | int Priority {get; set;} 23 | } 24 | ``` 25 | 26 | Simple flow for creating a `Priority-By-Integer` queue and adding an item: 27 | 28 | ```csharp 29 | // Create a new prioritized item. 30 | var itemWithPriority = new SomeClass { Priority = 0 }; 31 | 32 | // Initialize an unbounded priority-by-integer queue. 33 | var priorityQueue = new ConcurrentPriorityQueue, int>(); 34 | 35 | // Enqueue item and handle result. 36 | Result result = priorityQueue.Enqueue(itemWithPriority); 37 | ``` 38 | 39 | Use the `ConcurrentPriorityByIntegerQueue` implementation to simplify the above example: 40 | 41 | ```csharp 42 | var priorityQueue = new ConcurrentPriorityByIntegerQueue>(); 43 | ``` 44 | 45 | **Consume** items by priority/first-in-first-out policy, using `Dequeue()` and `Peek()`: 46 | 47 | ```csharp 48 | // Lower value -> Higher priority. 49 | var item1 = new SomeClass { Priority = 1 }; 50 | var item2 = new SomeClass { Priority = 0 }; 51 | var item3 = new SomeClass { Priority = 0 }; 52 | 53 | priorityQueue.Enqueue(item1); 54 | priorityQueue.Enqueue(item2); 55 | priorityQueue.Enqueue(item3); 56 | 57 | var result = priority.Dequeue(); // item2 58 | var result = priority.Dequeue(); // item3 59 | var result = priority.Dequeue(); // item1 60 | ``` 61 | 62 | **Iterating** over the collection will yield items according to their priority and position (FIFO): 63 | 64 | ```csharp 65 | var item1 = new SomeClass { Priority = 1 }; 66 | var item2 = new SomeClass { Priority = 0 }; 67 | var item3 = new SomeClass { Priority = 0 }; 68 | 69 | priorityQueue.Enqueue(item1); 70 | priorityQueue.Enqueue(item2); 71 | priorityQueue.Enqueue(item3); 72 | 73 | foreach(var item in priorityQueue) { 74 | // Iteration 1 -> item2 75 | // Iteration 2 -> item3 76 | // Iteration 3 -> item1 77 | } 78 | ``` 79 | 80 | `ConcurrentPriorityQueue` supports **Generic Priorities**. 81 | 82 | Implement your own **Business Priority** object and configure the queue to handle it: 83 | 84 | ```csharp 85 | // TimeToProcess class implements IEquatable, IComparable and overrides Object.GetHashCode(). 86 | public class TimeToProcess : IEquatable, IComparable { 87 | public decimal TimeInMilliseconds { get; set;} 88 | 89 | public int CompareTo(TimeToProcess other) => 90 | TimeInMilliseconds.CompareTo(other.TimeInMilliseconds); 91 | 92 | public bool Equals(TimeToProcess other) => 93 | TimeInMilliseconds.Equals(other.TimeInMilliseconds); 94 | 95 | public override int GetHashCode() => TimeInMilliseconds.GetHashCode(); 96 | } 97 | ``` 98 | 99 | ```csharp 100 | // BusinessPriorityItem implements IHavePriority 101 | public class BusinessPriorityItem : IHavePriority { 102 | TimeToProcess Priority {get; set;} 103 | } 104 | ``` 105 | 106 | ```csharp 107 | // Create a new prioritized item. 108 | var item = new BusinessPriorityItem { Priority = new TimeToProcess { TimeInMilliseconds = 0.25M } }; 109 | 110 | // Initialize an unbounded priority-by-TimeToProcess queue. 111 | var priorityQueue = new ConcurrentPriorityQueue, TimeToProcess>(); 112 | 113 | // Enqueue item and handle result. 114 | Result result = priorityQueue.Enqueue(item); 115 | ``` 116 | 117 | `ConcurrentPriorityQueue` can be **bounded** to a fixed amount of priorities: 118 | 119 | ```csharp 120 | // Create a bounded ConcurrentPriorityQueue to support a fixed amount of priorities. 121 | var maxAmountOfPriorities = 2; 122 | var priorityQueue = new ConcurrentPriorityByIntegerQueue>(maxAmountOfPriorities); 123 | 124 | Result result = PriorityQueue.Enqueue(new SomeClass {Priority = 0}); // result.OK 125 | Result result = PriorityQueue.Enqueue(new SomeClass {Priority = 1}); // result.OK 126 | Result result = PriorityQueue.Enqueue(new SomeClass {Priority = 2}); // result.Fail -> Queue supports [0, 1] 127 | Result result = PriorityQueue.Enqueue(new SomeClass {Priority = 0}); // result.OK 128 | ``` 129 | 130 | `ConcurrentPriorityQueue` can be **extended** to a `BlockingCollection` using the `ToBlockingCollection` extension method: 131 | 132 | ```csharp 133 | var blockingPriorityQueue = new ConcurrentPriorityByIntegerQueue>() 134 | .ToBlockingCollection(); 135 | 136 | foreach(var item in blockingPriorityQueue.GetConsumingEnumerable()) { 137 | // Do something... 138 | // Blocks until signaled on completion. 139 | } 140 | ``` 141 | 142 | ### Additional information and resources: 143 | 144 | - [IProducerConsumerCollection Documentation](https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.iproducerconsumercollection-1?view=netframework-4.8) 145 | - [BlockingCollection Documentation](https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.blockingcollection-1?view=netframework-4.8) 146 | - [Functional Extensions for C#](https://github.com/vkhorikov/CSharpFunctionalExtensions) 147 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | --------------------------------------------------------------------------------