├── .gitignore ├── Chan ├── BufferedChan │ └── BufferedChan.cs ├── Chan.cs ├── Chan.csproj ├── Chan.nuspec ├── Helpers │ ├── ChanUtility.cs │ └── ChanYieldEnumerator.cs ├── IChan.cs ├── Properties │ └── AssemblyInfo.cs └── UnbufferedChan │ ├── UnbufferedChan.cs │ └── UnbufferedChanReceiver.cs ├── Chan4Net.sln ├── ChanTests ├── BufferedChanTests.cs ├── ChanTests.csproj ├── ChanVsBlockingCollectionPerformanceTests.cs ├── Properties │ └── AssemblyInfo.cs └── UnbufferedChanTests.cs ├── CreateNuGetPackage.bat ├── LICENSE ├── README.md └── docs └── Perf-ChanVsBlockingCollection.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | *.suo 2 | TestResults 3 | bin 4 | obj 5 | *.DotSettings 6 | *.nupkg 7 | -------------------------------------------------------------------------------- /Chan/BufferedChan/BufferedChan.cs: -------------------------------------------------------------------------------- 1 | using Chan4Net.Helpers; 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | 7 | namespace Chan4Net.BufferedChan 8 | { 9 | internal class BufferedChan : IChan 10 | { 11 | private readonly ManualResetEventSlim _canAddEvent; 12 | private readonly ManualResetEventSlim _canTakeEvent; 13 | private readonly ConcurrentQueue _queue; 14 | private readonly int _size; 15 | 16 | public BufferedChan(int size) 17 | { 18 | if (size < 1) throw new ArgumentOutOfRangeException("size", size, "The size of a buffered channel must be greater than 1"); 19 | _size = size; 20 | _queue = new ConcurrentQueue(); 21 | _canTakeEvent = new ManualResetEventSlim(false); 22 | _canAddEvent = new ManualResetEventSlim(false); 23 | } 24 | 25 | public int Count 26 | { 27 | get { return _queue.Count; } 28 | } 29 | 30 | public bool IsClosed { get; private set; } 31 | 32 | public void Send(T item, CancellationToken cancellationToken) 33 | { 34 | while (_queue.Count == _size) 35 | { 36 | ChanUtility.AssertChanNotClosed(this); 37 | _canAddEvent.Wait(cancellationToken); 38 | } 39 | ChanUtility.AssertChanNotClosed(this); 40 | _queue.Enqueue(item); 41 | _canTakeEvent.Set(); 42 | } 43 | 44 | public void Send(T item) 45 | { 46 | Send(item, CancellationToken.None); 47 | } 48 | 49 | public void Close() 50 | { 51 | IsClosed = true; 52 | } 53 | 54 | public T Receive() 55 | { 56 | return Receive(CancellationToken.None); 57 | } 58 | 59 | public T Receive(CancellationToken cancellationToken) 60 | { 61 | while (true) 62 | { 63 | if (cancellationToken.IsCancellationRequested) 64 | { 65 | throw new OperationCanceledException(cancellationToken); 66 | } 67 | T item; 68 | if (_queue.TryDequeue(out item)) 69 | { 70 | _canAddEvent.Set(); 71 | return item; 72 | } 73 | if (_queue.Count == 0) 74 | { 75 | ChanUtility.AssertChanNotClosed(this); 76 | } 77 | _canTakeEvent.Wait(cancellationToken); 78 | } 79 | } 80 | 81 | public IEnumerable Yield() 82 | { 83 | return Yield(CancellationToken.None); 84 | } 85 | 86 | public IEnumerable Yield(CancellationToken cancellationToken) 87 | { 88 | var enumerator = new ChanYieldEnumerator(this, cancellationToken); 89 | while (enumerator.MoveNext()) 90 | { 91 | yield return enumerator.Current; 92 | } 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /Chan/Chan.cs: -------------------------------------------------------------------------------- 1 | using Chan4Net.BufferedChan; 2 | using Chan4Net.UnbufferedChan; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | 6 | namespace Chan4Net 7 | { 8 | /// 9 | /// Golang chan like implementation. 10 | /// 11 | /// 12 | public class Chan : IChan 13 | { 14 | private readonly IChan _chan; 15 | /// 16 | /// 17 | /// 18 | /// null or an integer no less than 1. if null or not specified, an unbuffered chan will be created. 19 | public Chan(int? size = null) 20 | { 21 | if (size.HasValue) 22 | { 23 | _chan = new BufferedChan(size.Value); 24 | } 25 | else 26 | { 27 | _chan = new UnbufferedChan(); 28 | } 29 | } 30 | /// 31 | /// Returns if the channel has been closed. You cannot continue adding item into a closed channel. 32 | /// However, items remaining in the channel can be taken and yielded until the channel is empty. 33 | /// 34 | public bool IsClosed 35 | { 36 | get { return _chan.IsClosed; } 37 | } 38 | /// 39 | /// Closes the channel. No more item can be sent into channel after this is called. 40 | /// 41 | public void Close() 42 | { 43 | _chan.Close(); 44 | } 45 | /// 46 | /// Sends an item into channel. 47 | /// For a buffered channel, If the channel is full, this method will block the current thread, 48 | /// until some item is taken. 49 | /// 50 | public void Send(T item) 51 | { 52 | _chan.Send(item); 53 | } 54 | /// 55 | /// Sends an item into channel. 56 | /// For a buffered channel, If the channel is full, this method will block the current thread, 57 | /// until some item is taken. 58 | /// If the cancel source is fired, this method will throw an OperationCanceledException. 59 | /// 60 | /// 61 | /// 62 | public void Send(T item, CancellationToken cancellationToken) 63 | { 64 | _chan.Send(item, cancellationToken); 65 | } 66 | /// 67 | /// Removes and returns an item from channel. If the channel is empty, this will block the current thread, 68 | /// until an item is sent into the channel. 69 | /// 70 | /// 71 | public T Receive() 72 | { 73 | return _chan.Receive(); 74 | } 75 | /// 76 | /// Removes and returns an item from channel. If the channel is empty, this will block the current thread, 77 | /// until an item is sent into the channel. 78 | /// If the cancel source is fired, this method will throw an OperationCanceledException. 79 | /// 80 | /// 81 | /// 82 | public T Receive(CancellationToken cancellationToken) 83 | { 84 | return _chan.Receive(cancellationToken); 85 | } 86 | /// 87 | /// Removes and returns elements from the channel. 88 | /// Empty channel will block the current thread. 89 | /// Unlike Receive(), cancelling token and closing channel won't throw exception but just break the loop. 90 | /// 91 | /// 92 | public IEnumerable Yield() 93 | { 94 | return _chan.Yield(); 95 | } 96 | /// 97 | /// Removes and returns elements from the channel. 98 | /// Empty channel will block the current thread. 99 | /// Unlike Receive(), cancelling token and closing channel won't throw exception but just break the loop. 100 | /// 101 | /// 102 | /// 103 | public IEnumerable Yield(CancellationToken cancellationToken) 104 | { 105 | return _chan.Yield(cancellationToken); 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /Chan/Chan.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard1.1;net40 5 | false 6 | false 7 | false 8 | false 9 | false 10 | false 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Chan/Chan.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Chan4Net 5 | 1.0.0 6 | jun.shao 7 | jun.shao 8 | https://github.com/superopengl/Chan4Net/blob/master/LICENSE 9 | https://github.com/superopengl/Chan4Net 10 | false 11 | A simple .NET implementation of Golang/Go chan 12 | Supports unbuffered/buffered chan 13 | Copyright 2017 14 | chan channel bufferred unbufferred queue 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chan/Helpers/ChanUtility.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Chan4Net.Helpers 4 | { 5 | internal static class ChanUtility 6 | { 7 | public static void AssertChanNotClosed(IChan chan) 8 | { 9 | if (chan.IsClosed) throw new InvalidOperationException("The chan has been closed"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chan/Helpers/ChanYieldEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | 6 | namespace Chan4Net.Helpers 7 | { 8 | internal class ChanYieldEnumerator : IEnumerator 9 | { 10 | private readonly CancellationToken _cancellationToken; 11 | private readonly IChan _target; 12 | 13 | public ChanYieldEnumerator(IChan target, CancellationToken cancellationToken) 14 | { 15 | _target = target; 16 | _cancellationToken = cancellationToken; 17 | } 18 | 19 | public void Dispose() 20 | { 21 | } 22 | 23 | public bool MoveNext() 24 | { 25 | try 26 | { 27 | Current = _target.Receive(_cancellationToken); 28 | return true; 29 | } 30 | catch (OperationCanceledException) 31 | { 32 | return false; 33 | } 34 | catch (InvalidOperationException) 35 | { 36 | return false; 37 | } 38 | } 39 | 40 | public void Reset() 41 | { 42 | throw new NotImplementedException(); 43 | } 44 | 45 | public T Current { get; private set; } 46 | 47 | object IEnumerator.Current 48 | { 49 | get { return Current; } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Chan/IChan.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading; 3 | 4 | namespace Chan4Net 5 | { 6 | /// 7 | /// Golang chan like implementation. 8 | /// 9 | /// 10 | internal interface IChan 11 | { 12 | /// 13 | /// Returns if the channel has been closed. You cannot continue adding item into a closed channel. 14 | /// However, items remaining in the channel can be taken and yielded until the channel is empty. 15 | /// 16 | bool IsClosed { get; } 17 | /// 18 | /// Closes the channel. No more item can be sent into channel after this is called. 19 | /// 20 | void Close(); 21 | /// 22 | /// Sends an item into channel. 23 | /// For a buffered channel, If the channel is full, this method will block the current thread, 24 | /// until some item is taken. 25 | /// 26 | void Send(T item); 27 | /// 28 | /// Sends an item into channel. 29 | /// For a buffered channel, If the channel is full, this method will block the current thread, 30 | /// until some item is taken. 31 | /// If the cancel source is fired, this method will throw an OperationCanceledException. 32 | /// 33 | /// 34 | /// 35 | void Send(T item, CancellationToken cancellationToken); 36 | /// 37 | /// Removes and returns an item from channel. If the channel is empty, this will block the current thread, 38 | /// until an item is sent into the channel. 39 | /// 40 | /// 41 | T Receive(); 42 | /// 43 | /// Removes and returns an item from channel. If the channel is empty, this will block the current thread, 44 | /// until an item is sent into the channel. 45 | /// If the cancel source is fired, this method will throw an OperationCanceledException. 46 | /// 47 | /// 48 | /// 49 | T Receive(CancellationToken cancellationToken); 50 | /// 51 | /// Removes and returns elements from the channel. 52 | /// Empty channel will block the current thread. 53 | /// Unlike Receive(), cancelling token and closing channel won't throw exception but just break the loop. 54 | /// 55 | /// 56 | IEnumerable Yield(); 57 | /// 58 | /// Removes and returns elements from the channel. 59 | /// Empty channel will block the current thread. 60 | /// Unlike Receive(), cancelling token and closing channel won't throw exception but just break the loop. 61 | /// 62 | /// 63 | /// 64 | IEnumerable Yield(CancellationToken cancellationToken); 65 | } 66 | } -------------------------------------------------------------------------------- /Chan/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | 9 | [assembly: AssemblyTitle("BufferedChan")] 10 | [assembly: AssemblyDescription("")] 11 | [assembly: AssemblyConfiguration("")] 12 | [assembly: AssemblyCompany("")] 13 | [assembly: AssemblyProduct("BufferedChan")] 14 | [assembly: AssemblyCopyright("Copyright © 2016")] 15 | [assembly: AssemblyTrademark("")] 16 | [assembly: AssemblyCulture("")] 17 | 18 | // Setting ComVisible to false makes the types in this assembly not visible 19 | // to COM components. If you need to access a type in this assembly from 20 | // COM, set the ComVisible attribute to true on that type. 21 | 22 | [assembly: ComVisible(false)] 23 | 24 | // The following GUID is for the ID of the typelib if this project is exposed to COM 25 | 26 | [assembly: Guid("fff8b5c8-960b-484d-9dfa-acdfc3389c65")] 27 | [assembly: InternalsVisibleTo("Chan4Net.Tests")] 28 | 29 | // Version information for an assembly consists of the following four values: 30 | // 31 | // Major Version 32 | // Minor Version 33 | // Build Number 34 | // Revision 35 | // 36 | // You can specify all the values or you can default the Build and Revision Numbers 37 | // by using the '*' as shown below: 38 | // [assembly: AssemblyVersion("1.0.*")] 39 | 40 | [assembly: AssemblyVersion("1.0.0.0")] 41 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /Chan/UnbufferedChan/UnbufferedChan.cs: -------------------------------------------------------------------------------- 1 | using Chan4Net.Helpers; 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | 7 | namespace Chan4Net.UnbufferedChan 8 | { 9 | internal class UnbufferedChan : IChan 10 | { 11 | private readonly ConcurrentQueue> _receivers; 12 | 13 | public UnbufferedChan() 14 | { 15 | _receivers = new ConcurrentQueue>(); 16 | } 17 | 18 | public bool IsClosed { get; private set; } 19 | 20 | public void Close() 21 | { 22 | IsClosed = true; 23 | } 24 | 25 | public void Send(T item) 26 | { 27 | Send(item, CancellationToken.None); 28 | } 29 | 30 | public void Send(T item, CancellationToken cancellationToken) 31 | { 32 | ChanUtility.AssertChanNotClosed(this); 33 | if (cancellationToken.IsCancellationRequested) 34 | throw new OperationCanceledException(cancellationToken); 35 | UnbufferedChanReceiver receiver; 36 | if (_receivers.Count == 0 || !_receivers.TryDequeue(out receiver)) 37 | throw new InvalidOperationException("No alive receiver for this no buffered chan."); 38 | receiver.WakeUp(() => item); 39 | } 40 | 41 | public T Receive() 42 | { 43 | return Receive(CancellationToken.None); 44 | } 45 | 46 | public T Receive(CancellationToken cancellationToken) 47 | { 48 | if (cancellationToken.IsCancellationRequested) 49 | throw new OperationCanceledException(cancellationToken); 50 | 51 | ChanUtility.AssertChanNotClosed(this); 52 | 53 | using (var receiver = new UnbufferedChanReceiver()) 54 | { 55 | _receivers.Enqueue(receiver); 56 | return receiver.WaitForValue(cancellationToken); 57 | } 58 | } 59 | 60 | public IEnumerable Yield() 61 | { 62 | return Yield(CancellationToken.None); 63 | } 64 | 65 | public IEnumerable Yield(CancellationToken cancellationToken) 66 | { 67 | var enumerator = new ChanYieldEnumerator(this, cancellationToken); 68 | while (enumerator.MoveNext()) 69 | { 70 | yield return enumerator.Current; 71 | } 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /Chan/UnbufferedChan/UnbufferedChanReceiver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace Chan4Net.UnbufferedChan 5 | { 6 | internal class UnbufferedChanReceiver : IDisposable 7 | { 8 | private readonly ManualResetEventSlim _eventHandler; 9 | private Func _getValueFunc; 10 | 11 | public UnbufferedChanReceiver() 12 | { 13 | _eventHandler = new ManualResetEventSlim(false); 14 | } 15 | 16 | public void Dispose() 17 | { 18 | _eventHandler.Dispose(); 19 | } 20 | 21 | public void WakeUp(Func getValueFunc) 22 | { 23 | if (getValueFunc == null) throw new ArgumentNullException("getValueFunc"); 24 | _getValueFunc = getValueFunc; 25 | _eventHandler.Set(); 26 | } 27 | 28 | public T WaitForValue(CancellationToken cancellationToken) 29 | { 30 | while (_getValueFunc == null) 31 | { 32 | _eventHandler.Wait(cancellationToken); 33 | } 34 | return _getValueFunc(); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Chan4Net.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chan", "Chan\Chan.csproj", "{FFF8B5C8-960B-484D-9DFA-ACDFC3389C65}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChanTests", "ChanTests\ChanTests.csproj", "{A446C06F-8F57-46A5-B3A9-461DD5CE9F36}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {FFF8B5C8-960B-484D-9DFA-ACDFC3389C65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {FFF8B5C8-960B-484D-9DFA-ACDFC3389C65}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {FFF8B5C8-960B-484D-9DFA-ACDFC3389C65}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {FFF8B5C8-960B-484D-9DFA-ACDFC3389C65}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {A446C06F-8F57-46A5-B3A9-461DD5CE9F36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {A446C06F-8F57-46A5-B3A9-461DD5CE9F36}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {A446C06F-8F57-46A5-B3A9-461DD5CE9F36}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {A446C06F-8F57-46A5-B3A9-461DD5CE9F36}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /ChanTests/BufferedChanTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using Chan4Net.BufferedChan; 9 | 10 | namespace Chan4Net.Tests 11 | { 12 | [TestClass] 13 | public class BufferedChanTests 14 | { 15 | private readonly TimeSpan _awaitTimeout = TimeSpan.FromMilliseconds(1000); 16 | private readonly TimeSpan _slowActionLetency = TimeSpan.FromMilliseconds(500); 17 | 18 | [TestMethod] 19 | [ExpectedException(typeof (ArgumentOutOfRangeException))] 20 | public void Ctor_ChanSizeZero_ShouldThrow() 21 | { 22 | var sut = new BufferedChan(0); 23 | } 24 | 25 | [TestMethod] 26 | public void Send_LessThanSize_SendShouldNotBeBlocked() 27 | { 28 | var sut = new BufferedChan(2); 29 | var called = false; 30 | 31 | var producer = Task.Run(() => 32 | { 33 | sut.Send(1); 34 | sut.Send(2); 35 | called = true; 36 | }); 37 | 38 | producer.Wait(); 39 | 40 | Assert.AreEqual(2, sut.Count); 41 | Assert.IsTrue(called); 42 | } 43 | 44 | [TestMethod] 45 | public void Send_AfterClosed_ShouldThrow() 46 | { 47 | var sut = new BufferedChan(2); 48 | sut.Send(1); 49 | sut.Close(); 50 | 51 | Exception exception = null; 52 | try 53 | { 54 | sut.Send(2); 55 | } 56 | catch (Exception ex) 57 | { 58 | exception = ex; 59 | } 60 | 61 | Assert.AreEqual(1, sut.Count); 62 | Assert.IsTrue(sut.IsClosed); 63 | Assert.IsInstanceOfType(exception, typeof (InvalidOperationException)); 64 | } 65 | 66 | [TestMethod] 67 | public void Send_MoreThanSize_SendShouldBeBlocked() 68 | { 69 | var sut = new BufferedChan(2); 70 | var called = false; 71 | var producer = Task.Run(() => 72 | { 73 | sut.Send(1); 74 | sut.Send(2); 75 | sut.Send(3); 76 | called = true; 77 | }); 78 | 79 | producer.Wait(_awaitTimeout); 80 | 81 | Assert.AreEqual(2, sut.Count); 82 | Assert.IsFalse(called); 83 | } 84 | 85 | [TestMethod] 86 | public void SendMany_ReceiveFew_SendShouldBeBlocked() 87 | { 88 | var sut = new BufferedChan(2); 89 | bool? called = null; 90 | var producer = Task.Run(() => 91 | { 92 | sut.Send(1); 93 | sut.Send(2); 94 | sut.Send(3); 95 | sut.Send(4); 96 | sut.Send(5); 97 | called = false; 98 | sut.Send(6); 99 | called = true; 100 | }); 101 | 102 | var items = new List {sut.Receive(), sut.Receive(), sut.Receive()}; 103 | 104 | producer.Wait(_awaitTimeout); 105 | 106 | Assert.AreEqual(2, sut.Count); 107 | Assert.IsFalse(called != null && called.Value); 108 | CollectionAssert.AreEquivalent(new[] {1, 2, 3}, items.ToArray()); 109 | } 110 | 111 | [TestMethod] 112 | public void Send_CancellationToken_ShouldThrow() 113 | { 114 | var sut = new BufferedChan(2); 115 | Exception exception = null; 116 | var cts = new CancellationTokenSource(); 117 | var producer = Task.Run(() => 118 | { 119 | sut.Send(1); 120 | sut.Send(2); 121 | try 122 | { 123 | sut.Send(3, cts.Token); 124 | } 125 | catch (Exception ex) 126 | { 127 | exception = ex; 128 | } 129 | }); 130 | 131 | producer.Wait(_awaitTimeout); 132 | cts.Cancel(); 133 | producer.Wait(); // Await the catch block to finish 134 | 135 | Assert.AreEqual(2, sut.Count); 136 | Assert.IsInstanceOfType(exception, typeof (OperationCanceledException)); 137 | } 138 | 139 | [TestMethod] 140 | public void SendFew_ReceiveMany_ReceiveShouldBeBlocked() 141 | { 142 | var sut = new BufferedChan(2); 143 | sut.Send(1); 144 | sut.Send(2); 145 | 146 | bool? called = null; 147 | var items = new List(); 148 | var consumer = Task.Run(() => 149 | { 150 | items.Add(sut.Receive()); 151 | items.Add(sut.Receive()); 152 | called = false; 153 | items.Add(sut.Receive()); 154 | called = true; 155 | }); 156 | 157 | consumer.Wait(_awaitTimeout); 158 | 159 | Assert.AreEqual(0, sut.Count); 160 | Assert.IsFalse(called != null && called.Value); 161 | CollectionAssert.AreEquivalent(new[] {1, 2}, items.ToArray()); 162 | } 163 | 164 | [TestMethod] 165 | public void Receive_FromEmptyChan_ReceiveShouldBeBlocked() 166 | { 167 | var sut = new BufferedChan(2); 168 | var called = false; 169 | var producer = Task.Run(() => 170 | { 171 | var item = sut.Receive(); 172 | called = true; 173 | }); 174 | 175 | producer.Wait(_awaitTimeout); 176 | 177 | Assert.AreEqual(0, sut.Count); 178 | Assert.IsFalse(called); 179 | } 180 | 181 | [TestMethod] 182 | public void Receive_CancellationToken_ShouldThrow() 183 | { 184 | var sut = new BufferedChan(2); 185 | var cts = new CancellationTokenSource(); 186 | Exception exception = null; 187 | var consumer = Task.Run(() => 188 | { 189 | try 190 | { 191 | sut.Receive(cts.Token); 192 | } 193 | catch (Exception ex) 194 | { 195 | exception = ex; 196 | } 197 | }); 198 | 199 | consumer.Wait(_awaitTimeout); 200 | cts.Cancel(); 201 | consumer.Wait(); // Await the catch block to finish 202 | 203 | Assert.IsInstanceOfType(exception, typeof (OperationCanceledException)); 204 | } 205 | 206 | [TestMethod] 207 | public void Receive_FromEmptyChanAfterClosed_ShouldThrow() 208 | { 209 | var sut = new BufferedChan(2); 210 | sut.Close(); 211 | Exception exception = null; 212 | try 213 | { 214 | sut.Receive(); 215 | } 216 | catch (Exception ex) 217 | { 218 | exception = ex; 219 | } 220 | 221 | Assert.AreEqual(0, sut.Count); 222 | Assert.IsTrue(sut.IsClosed); 223 | Assert.IsInstanceOfType(exception, typeof (InvalidOperationException)); 224 | } 225 | 226 | [TestMethod] 227 | public void Receive_FromNonEmptyChan_ShouldNotBeBlocked() 228 | { 229 | var sut = new BufferedChan(2); 230 | sut.Send(1); 231 | sut.Send(2); 232 | 233 | var item1 = sut.Receive(); 234 | var item2 = sut.Receive(); 235 | 236 | Assert.AreEqual(0, sut.Count); 237 | Assert.AreEqual(1, item1); 238 | Assert.AreEqual(2, item2); 239 | } 240 | 241 | [TestMethod] 242 | public void Yield_NotClosedChan_ShouldBeBlocked() 243 | { 244 | var sut = new BufferedChan(2); 245 | var producer = Task.Run(() => 246 | { 247 | sut.Send(1); 248 | sut.Send(2); 249 | sut.Send(3); 250 | }); 251 | 252 | var items = new List(); 253 | var called = false; 254 | var consumer = Task.Run(() => 255 | { 256 | foreach (var i in sut.Yield()) 257 | { 258 | items.Add(i); 259 | } 260 | called = true; 261 | }); 262 | 263 | producer.Wait(); 264 | consumer.Wait(_awaitTimeout); 265 | 266 | Assert.AreEqual(3, items.Count); 267 | Assert.IsFalse(called); 268 | } 269 | 270 | [TestMethod] 271 | public void Yield_ClosedChan_ShouldNotBeBlocked() 272 | { 273 | var sut = new BufferedChan(2); 274 | var producer = Task.Run(() => 275 | { 276 | sut.Send(1); 277 | sut.Send(2); 278 | sut.Send(3); 279 | }); 280 | 281 | var items = new List(); 282 | var called = false; 283 | var consumer = Task.Run(() => 284 | { 285 | foreach (var i in sut.Yield()) 286 | { 287 | items.Add(i); 288 | } 289 | called = true; 290 | }); 291 | 292 | producer.Wait(); 293 | sut.Close(); 294 | consumer.Wait(_awaitTimeout); 295 | 296 | Assert.AreEqual(3, items.Count); 297 | Assert.IsTrue(called); 298 | } 299 | 300 | [TestMethod] 301 | public void ProducerConsumer_MoreThanChanSize() 302 | { 303 | var sut = new BufferedChan(2); 304 | var producerCalled = false; 305 | var totalItemCount = 100; 306 | var producer = Task.Run(() => 307 | { 308 | for (var i = 1; i <= totalItemCount; i++) 309 | { 310 | sut.Send(i); 311 | } 312 | producerCalled = true; 313 | }); 314 | 315 | var consumerCalled = false; 316 | var items = new List(); 317 | var consumer = Task.Run(() => 318 | { 319 | for (var i = 1; i <= totalItemCount; i++) 320 | { 321 | items.Add(sut.Receive()); 322 | } 323 | consumerCalled = true; 324 | }); 325 | 326 | Task.WaitAll(producer, consumer); 327 | 328 | Assert.AreEqual(0, sut.Count); 329 | Assert.IsTrue(producerCalled); 330 | Assert.IsTrue(consumerCalled); 331 | CollectionAssert.AreEquivalent(Enumerable.Range(1, totalItemCount).ToArray(), items.ToArray()); 332 | } 333 | 334 | [TestMethod] 335 | public void ProducerConsumer_SlowProducer_FastConsumer() 336 | { 337 | var sut = new BufferedChan(2); 338 | var producerCalled = false; 339 | var producer = Task.Run(async () => 340 | { 341 | await Task.Delay(_slowActionLetency); 342 | sut.Send(1); 343 | await Task.Delay(_slowActionLetency); 344 | sut.Send(2); 345 | await Task.Delay(_slowActionLetency); 346 | sut.Send(3); 347 | producerCalled = true; 348 | }); 349 | 350 | var consumerCalled = false; 351 | var items = new List(); 352 | var consumer = Task.Run(() => 353 | { 354 | items.Add(sut.Receive()); 355 | items.Add(sut.Receive()); 356 | items.Add(sut.Receive()); 357 | consumerCalled = true; 358 | }); 359 | 360 | Task.WaitAll(producer, consumer); 361 | 362 | Assert.AreEqual(0, sut.Count); 363 | Assert.IsTrue(producerCalled); 364 | Assert.IsTrue(consumerCalled); 365 | CollectionAssert.AreEquivalent(new[] {1, 2, 3}, items.ToArray()); 366 | } 367 | 368 | [TestMethod] 369 | public void ProducerConsumer_FastProducer_SlowConsumer() 370 | { 371 | var sut = new BufferedChan(2); 372 | var producerCalled = false; 373 | var producer = Task.Run(() => 374 | { 375 | sut.Send(1); 376 | sut.Send(2); 377 | sut.Send(3); 378 | producerCalled = true; 379 | }); 380 | 381 | var consumerCalled = false; 382 | var items = new List(); 383 | var consumer = Task.Run(async () => 384 | { 385 | await Task.Delay(_slowActionLetency); 386 | items.Add(sut.Receive()); 387 | await Task.Delay(_slowActionLetency); 388 | items.Add(sut.Receive()); 389 | await Task.Delay(_slowActionLetency); 390 | items.Add(sut.Receive()); 391 | consumerCalled = true; 392 | }); 393 | 394 | Task.WaitAll(producer, consumer); 395 | 396 | Assert.AreEqual(0, sut.Count); 397 | Assert.IsTrue(producerCalled); 398 | Assert.IsTrue(consumerCalled); 399 | CollectionAssert.AreEquivalent(new[] {1, 2, 3}, items.ToArray()); 400 | } 401 | 402 | [TestMethod] 403 | public void ProducerConsumer_MultipleProducers_MultipleConsumers() 404 | { 405 | var sut = new BufferedChan(2); 406 | var producer1Called = false; 407 | var producer1 = Task.Run(() => 408 | { 409 | sut.Send(1); 410 | sut.Send(2); 411 | sut.Send(3); 412 | producer1Called = true; 413 | }); 414 | 415 | var producer2Called = false; 416 | var producer2 = Task.Run(() => 417 | { 418 | sut.Send(4); 419 | sut.Send(5); 420 | sut.Send(6); 421 | producer2Called = true; 422 | }); 423 | 424 | var items = new ConcurrentBag(); 425 | var consumer1Called = false; 426 | var consumer1 = Task.Run(() => 427 | { 428 | items.Add(sut.Receive()); 429 | items.Add(sut.Receive()); 430 | items.Add(sut.Receive()); 431 | consumer1Called = true; 432 | }); 433 | 434 | var consumer2Called = false; 435 | var consumer2 = Task.Run(() => 436 | { 437 | items.Add(sut.Receive()); 438 | items.Add(sut.Receive()); 439 | items.Add(sut.Receive()); 440 | consumer2Called = true; 441 | }); 442 | 443 | Task.WaitAll(producer1, producer2, consumer1, consumer2); 444 | 445 | Assert.AreEqual(0, sut.Count); 446 | Assert.IsTrue(producer1Called); 447 | Assert.IsTrue(producer2Called); 448 | Assert.IsTrue(consumer1Called); 449 | Assert.IsTrue(consumer2Called); 450 | CollectionAssert.AreEquivalent(new[] {1, 2, 3, 4, 5, 6}, items.ToArray()); 451 | } 452 | 453 | [TestMethod] 454 | public void ProducerConsumer_SingleProducer_MultipleConsumers() 455 | { 456 | var sut = new BufferedChan(2); 457 | var producerCalled = false; 458 | var producer = Task.Run(() => 459 | { 460 | sut.Send(1); 461 | sut.Send(2); 462 | sut.Send(3); 463 | sut.Send(4); 464 | sut.Send(5); 465 | sut.Send(6); 466 | producerCalled = true; 467 | }); 468 | 469 | var items = new ConcurrentBag(); 470 | var consumer1Called = false; 471 | var consumer1 = Task.Run(() => 472 | { 473 | items.Add(sut.Receive()); 474 | items.Add(sut.Receive()); 475 | items.Add(sut.Receive()); 476 | consumer1Called = true; 477 | }); 478 | 479 | var consumer2Called = false; 480 | var consumer2 = Task.Run(() => 481 | { 482 | items.Add(sut.Receive()); 483 | items.Add(sut.Receive()); 484 | items.Add(sut.Receive()); 485 | consumer2Called = true; 486 | }); 487 | 488 | Task.WaitAll(producer, consumer1, consumer2); 489 | 490 | Assert.AreEqual(0, sut.Count); 491 | Assert.IsTrue(producerCalled); 492 | Assert.IsTrue(consumer1Called); 493 | Assert.IsTrue(consumer2Called); 494 | CollectionAssert.AreEquivalent(new[] {1, 2, 3, 4, 5, 6}, items.ToArray()); 495 | } 496 | 497 | [TestMethod] 498 | public void ProducerConsumer_MultipleProducers_SingleConsumer() 499 | { 500 | var sut = new BufferedChan(2); 501 | var producer1Called = false; 502 | var producer1 = Task.Run(() => 503 | { 504 | sut.Send(1); 505 | sut.Send(2); 506 | sut.Send(3); 507 | producer1Called = true; 508 | }); 509 | 510 | var producer2Called = false; 511 | var producer2 = Task.Run(() => 512 | { 513 | sut.Send(4); 514 | sut.Send(5); 515 | sut.Send(6); 516 | producer2Called = true; 517 | }); 518 | 519 | var items = new ConcurrentBag(); 520 | var consumerCalled = false; 521 | var consumer = Task.Run(() => 522 | { 523 | items.Add(sut.Receive()); 524 | items.Add(sut.Receive()); 525 | items.Add(sut.Receive()); 526 | items.Add(sut.Receive()); 527 | items.Add(sut.Receive()); 528 | items.Add(sut.Receive()); 529 | consumerCalled = true; 530 | }); 531 | 532 | Task.WaitAll(producer1, producer2, consumer); 533 | 534 | Assert.AreEqual(0, sut.Count); 535 | Assert.IsTrue(producer1Called); 536 | Assert.IsTrue(producer2Called); 537 | Assert.IsTrue(consumerCalled); 538 | CollectionAssert.AreEquivalent(new[] {1, 2, 3, 4, 5, 6}, items.ToArray()); 539 | } 540 | } 541 | } -------------------------------------------------------------------------------- /ChanTests/ChanTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {A446C06F-8F57-46A5-B3A9-461DD5CE9F36} 7 | Library 8 | Properties 9 | Chan4Net.Tests 10 | Chan4Net.Tests 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | 22 | true 23 | full 24 | false 25 | bin\Debug\ 26 | DEBUG;TRACE 27 | prompt 28 | 4 29 | false 30 | 31 | 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | {FFF8B5C8-960B-484D-9DFA-ACDFC3389C65} 64 | Chan 65 | 66 | 67 | 68 | 69 | 70 | 71 | False 72 | 73 | 74 | False 75 | 76 | 77 | False 78 | 79 | 80 | False 81 | 82 | 83 | 84 | 85 | 86 | 87 | 94 | -------------------------------------------------------------------------------- /ChanTests/ChanVsBlockingCollectionPerformanceTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Chan4Net; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace Chan4Net.Tests 10 | { 11 | [TestClass] 12 | public class ChanVsBlockingCollectionPerformanceTests 13 | { 14 | [TestMethod] 15 | public void OneProducer_OneConsumer_1Buffer_100000Items() 16 | { 17 | OneProducer_OneConsumer(1, 100000, 10); 18 | } 19 | 20 | [TestMethod] 21 | public void OneProducer_OneConsumer_1000Buffer_100000Items() 22 | { 23 | OneProducer_OneConsumer(1000, 100000, 10); 24 | } 25 | 26 | [TestMethod] 27 | public void OneProducer_OneConsumer_100000Buffer_100000Items() 28 | { 29 | OneProducer_OneConsumer(100000, 100000, 10); 30 | } 31 | 32 | private void OneProducer_OneConsumer(int capacity, int itemCount, int repeatTimes) 33 | { 34 | Console.WriteLine("Buffer size: {0}, Total items: {1}, by running {2} times", capacity, itemCount, 35 | repeatTimes); 36 | new PerformanceCaseRepeatedRunner("BufferedChan", repeatTimes, 37 | () => OneProducer_OneConsumer_Chan(capacity, itemCount)).Run(); 38 | new PerformanceCaseRepeatedRunner("BlockingCollection", repeatTimes, 39 | () => OneProducer_OneConsumer_BlockingCollection(capacity, itemCount)).Run(); 40 | } 41 | 42 | private void OneProducer_OneConsumer_Chan(int capacity, int itemCount) 43 | { 44 | var chan = new Chan(capacity); 45 | var producer = Task.Run(() => 46 | { 47 | foreach (var i in Enumerable.Range(0, itemCount)) 48 | { 49 | chan.Send(i); 50 | } 51 | chan.Close(); 52 | }); 53 | 54 | var consumer = Task.Run(() => 55 | { 56 | foreach (var i in chan.Yield()) 57 | { 58 | } 59 | }); 60 | 61 | Task.WaitAll(producer, consumer); 62 | } 63 | 64 | private void OneProducer_OneConsumer_BlockingCollection(int capacity, int itemCount) 65 | { 66 | var blockingCollection = new BlockingCollection(capacity); 67 | var producer = Task.Run(() => 68 | { 69 | foreach (var i in Enumerable.Range(0, itemCount)) 70 | { 71 | blockingCollection.Add(i); 72 | } 73 | blockingCollection.CompleteAdding(); 74 | }); 75 | 76 | var consumer = Task.Run(() => 77 | { 78 | foreach (var i in blockingCollection.GetConsumingEnumerable()) 79 | { 80 | } 81 | }); 82 | 83 | Task.WaitAll(producer, consumer); 84 | } 85 | 86 | private class PerformanceCaseRepeatedRunner 87 | { 88 | private readonly Action _action; 89 | private readonly string _label; 90 | private readonly int _repeatTimes; 91 | 92 | public PerformanceCaseRepeatedRunner(string label, int repeatTimes, Action action) 93 | { 94 | _label = label; 95 | _repeatTimes = repeatTimes; 96 | _action = action; 97 | } 98 | 99 | public void Run() 100 | { 101 | var sw = Stopwatch.StartNew(); 102 | foreach (var i in Enumerable.Range(0, _repeatTimes)) 103 | { 104 | _action(); 105 | } 106 | sw.Stop(); 107 | Console.WriteLine(@"{0}: 108 | Average time: {1} ms ({2} ticks)", _label, sw.ElapsedMilliseconds/_repeatTimes, sw.ElapsedTicks/_repeatTimes); 109 | } 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /ChanTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("ChanTests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("ChanTests")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("a446c06f-8f57-46a5-b3a9-461dd5ce9f36")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /ChanTests/UnbufferedChanTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using Chan4Net.UnbufferedChan; 8 | 9 | namespace Chan4Net.Tests 10 | { 11 | [TestClass] 12 | public class UnbufferedChanTests 13 | { 14 | private readonly TimeSpan _awaitTimeout = TimeSpan.FromMilliseconds(100); 15 | private readonly TimeSpan _slowActionLetency = TimeSpan.FromMilliseconds(100); 16 | 17 | [TestMethod] 18 | public void Receive_ShouldBeBlocked_IfNoOneSend() 19 | { 20 | var chan = new UnbufferedChan(); 21 | var called = false; 22 | var task = Task.Run(() => 23 | { 24 | chan.Receive(); 25 | called = true; 26 | }); 27 | 28 | task.Wait(_awaitTimeout); 29 | 30 | Assert.IsFalse(called); 31 | } 32 | 33 | [TestMethod] 34 | public void Receive_ShouldGetTheSameObjectThatSenderSent() 35 | { 36 | var chan = new UnbufferedChan(); 37 | var item = new object(); 38 | object result = null; 39 | var receiver = Task.Run(() => 40 | { 41 | Thread.Sleep(_slowActionLetency); 42 | chan.Send(item); 43 | }); 44 | 45 | result = chan.Receive(); 46 | receiver.Wait(); 47 | 48 | Assert.AreSame(item, result); 49 | } 50 | 51 | [TestMethod] 52 | public void Receive_ShouldNotBeBlocked_OnceOneSend() 53 | { 54 | var chan = new UnbufferedChan(); 55 | var called = false; 56 | var item = 0; 57 | var receiver = Task.Run(() => 58 | { 59 | item = chan.Receive(); 60 | called = true; 61 | }); 62 | 63 | Thread.Sleep(_slowActionLetency); 64 | chan.Send(1); // Make sure Receive() is called before Send() 65 | 66 | receiver.Wait(); 67 | 68 | Assert.AreEqual(1, item); 69 | Assert.IsTrue(called); 70 | } 71 | 72 | [TestMethod] 73 | public void Receive_RaceCondition_OnlyOneCanGetTheSentItemEachTime() 74 | { 75 | var chan = new UnbufferedChan(); 76 | var items = new ConcurrentBag(); 77 | var receiver1 = Task.Run(() => items.Add(chan.Receive())); 78 | var receiver2 = Task.Run(() => items.Add(chan.Receive())); 79 | var receiver3 = Task.Run(() => items.Add(chan.Receive())); 80 | 81 | Thread.Sleep(_slowActionLetency); 82 | chan.Send(1); 83 | 84 | Task.WaitAll(new[] { receiver1, receiver2, receiver3 }, _awaitTimeout); 85 | 86 | CollectionAssert.AreEquivalent(new[] { 1 }, items.ToArray()); 87 | } 88 | 89 | [TestMethod] 90 | public void Receive_RaceCondition_OneItemIsReceivedOnlyOnce() 91 | { 92 | var chan = new UnbufferedChan(); 93 | var items = new ConcurrentBag(); 94 | var samples = Enumerable.Range(0, 3).ToArray(); 95 | var receivers = samples.Select(i => { return Task.Run(() => items.Add(chan.Receive())); }).ToArray(); 96 | 97 | Thread.Sleep((int)_slowActionLetency.TotalMilliseconds); 98 | foreach (var i in samples) 99 | { 100 | chan.Send(i); 101 | } 102 | 103 | Task.WaitAll(receivers); 104 | 105 | CollectionAssert.AreEquivalent(samples, items.ToArray()); 106 | } 107 | 108 | [TestMethod] 109 | public void Receive_NoSend_NoBufferedChan_ShouldBlock() 110 | { 111 | var sut = new UnbufferedChan(); 112 | var called = false; 113 | var receiver = Task.Run(() => 114 | { 115 | sut.Receive(); 116 | called = true; 117 | }); 118 | 119 | receiver.Wait(_awaitTimeout); 120 | 121 | Assert.IsFalse(called); 122 | } 123 | 124 | [TestMethod] 125 | public void Send_NoReceiver_NoBufferedChan_ShouldThrow() 126 | { 127 | var sut = new UnbufferedChan(); 128 | Exception exception = null; 129 | try 130 | { 131 | sut.Send(1); 132 | } 133 | catch (Exception ex) 134 | { 135 | exception = ex; 136 | } 137 | 138 | Assert.IsInstanceOfType(exception, typeof(InvalidOperationException)); 139 | } 140 | } 141 | } -------------------------------------------------------------------------------- /CreateNuGetPackage.bat: -------------------------------------------------------------------------------- 1 | nuget pack Chan\Chan.csproj -properties Configuration=Release -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Jun Shao 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 | 2 | 3 | # Chan4Net 4 | A simple C# implementation of Golang/Go `chan` (https://tour.golang.org/concurrency/2). 5 | 6 | ## Installation 7 | NuGet package is avaiable via https://www.nuget.org/packages/Chan4Net. 8 | ``` 9 | Install-Package Chan4Net 10 | ``` 11 | 12 | ## Performance 13 | The automated performance tests are included in the test project. You can run on you machine. 14 | `Chan4Net` beats `BlockingCollection` on my local as below. 15 | 16 | ![Performance Chan vs BlockingCollection](docs/Perf-ChanVsBlockingCollection.jpg) 17 | 18 | ## APIs 19 | 20 | ### Create a chan of a type. 21 | ```csharp 22 | // A buffered chan 23 | var bufferedChan = new Chan(2); // Size must be >= 1 for a buffered channel. 24 | 25 | // An unbuffered chan 26 | var unbufferedChan = new Chan(); 27 | ``` 28 | 29 | ### `Send()` item 30 | ```csharp 31 | var chan = new Chan(2); 32 | chan.Send(1); 33 | chan.Send(2); 34 | chan.Send(3); // Will block the current thread because the channel is full 35 | ``` 36 | 37 | ### `Receive()` item 38 | ```csharp 39 | var chan = new Chan(2); 40 | chan.Send(1); 41 | chan.Send(2); 42 | 43 | var a = chan.Receive(); // a == 1 44 | var b = chan.Receive(); // b == 2 45 | var c = chan.Receive(); // Will block the current thread because the channel is empty. 46 | ``` 47 | 48 | ### `Yield()` items 49 | ```csharp 50 | var chan = new Chan(2); 51 | chan.Send(1); 52 | chan.Send(2); 53 | 54 | foreach(var item in chan.Yield()) { 55 | Console.WriteLine(item); // Outputs 1, 2 and then block and wait, because the channel is empty. 56 | } 57 | 58 | Console.WriteLine("Will never come to this line"); 59 | ``` 60 | 61 | ### `Close()` channel 62 | Sending item to a closed channel will throw exception. 63 | ```csharp 64 | var chan = new Chan(2); 65 | chan.Send(1); 66 | chan.Close(); 67 | 68 | chan.Send(2); // Here throws InvalidOperationException, because one cannot send item into a closed channel. 69 | ``` 70 | Receiving item from a closed AND empty channel will throw exception. 71 | ```csharp 72 | var chan = new Chan(2); 73 | chan.Send(1) 74 | chan.Close(); 75 | 76 | var a = chan.Receive(); // a == 1 77 | var b = chan.Receive(); // Here throws InvalidOperationException because no more item in the closed channel. 78 | ``` 79 | 80 | Calling `Close()` will release the blocking `Yield()`. 81 | ```csharp 82 | var chan = new Chan(2); 83 | chan.Send(1); 84 | chan.Send(2); 85 | chan.Close(); 86 | 87 | foreach(var item in chan.Yield()) { 88 | Console.WriteLine(item); // Outputs 1 and 2. 89 | } 90 | 91 | Console.WriteLine("Done"); // Outputs "Done" 92 | ``` 93 | ## Code Samples 94 | Please read below code as C# psuedo code. Some infinite loops and thread sleepings don't make sense in reality. 95 | ### `Chan` as infinite message queue - slow producer and fast consumer 96 | ```csharp 97 | var chan = new Chan(2); 98 | 99 | var producer = Task.Run(() => { 100 | while(true) { 101 | Thread.Sleep(1000); 102 | chan.Send(SomeRandomInt()); // Send an item every second. 103 | } 104 | }); 105 | 106 | var consumer = Task.Run(() => { 107 | foreach(var item in chan.Yield()) { 108 | Console.WriteLine(item); // Outputs an item once it exists in channel. 109 | } 110 | }); 111 | 112 | Task.WaitAll(producer, consumer); // Wait for ever because the channel is never closed. 113 | ``` 114 | 115 | ### `Chan` as buffer/pipeline - fast producer and slow consumer 116 | ```csharp 117 | var chan = new Chan(2); 118 | 119 | var producer = Task.Run(() => { 120 | chan.Send(1); 121 | chan.Send(2); 122 | chan.Send(3); 123 | chan.Send(4); 124 | chan.Send(5); 125 | chan.Close(); 126 | }); 127 | 128 | var consumer = Task.Run(() => { 129 | foreach(var item in chan.Yield()) { 130 | Thread.Sleep(1000); 131 | Console.WriteLine(item); // Outputs 1, 2, 3, 4, 5 132 | } 133 | // Can come to this line because the channel is closed. 134 | }); 135 | 136 | Task.WaitAll(producer, consumer); 137 | Console.WriteLine("Done"); // Outputs "Done" 138 | ``` 139 | ### `Chan` as loadbalancer - multiple consumers 140 | ```csharp 141 | var chan = new Chan(2); 142 | 143 | var boss = Task.Run(() => { 144 | while(true) { 145 | // Create works here 146 | chan.Send(0); 147 | } 148 | }); 149 | 150 | var worker1 = Task.Run(() => { 151 | foreach(var num in chan.Yield()) { 152 | // Worker1 works here slowly 153 | Thread.Sleep(1000); 154 | } 155 | }); 156 | 157 | var worker2 = Task.Run(() => { 158 | foreach(var num in chan.Yield()) { 159 | // Worker2 works here slowly 160 | Thread.Sleep(1000); 161 | } 162 | }); 163 | 164 | Task.WaitAll(boss, worker1, worker2); 165 | ``` 166 | ### `Chan` as Pub/Sub - multiple producers and multiple subscribers 167 | ```csharp 168 | var chan = new Chan(2); 169 | 170 | var publisher1 = Task.Run(() => { 171 | while(true) { 172 | // Create works here 173 | chan.Send(1); 174 | } 175 | }); 176 | 177 | var publisher2 = Task.Run(() => { 178 | while(true) { 179 | // Create works here 180 | chan.Send(2); 181 | } 182 | }); 183 | 184 | var subscriber1 = Task.Run(() => { 185 | foreach(var num in chan.Yield()) { 186 | if(num == 1) { 187 | // Does something. 188 | } else { 189 | chan.Send(num); // Send back to channel 190 | } 191 | } 192 | }); 193 | 194 | var subscriber2 = Task.Run(() => { 195 | foreach(var num in chan.Yield()) { 196 | if(num == 2) { 197 | // Does something. 198 | } else { 199 | chan.Send(num); // Send back to channel 200 | } 201 | } 202 | }); 203 | 204 | Task.WaitAll(publisher1, publisher2, subscriber1, subscriber2); 205 | ``` 206 | -------------------------------------------------------------------------------- /docs/Perf-ChanVsBlockingCollection.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/superopengl/Chan4Net/88f2abb34f739cf39f926db0076e7c7d8675d22f/docs/Perf-ChanVsBlockingCollection.jpg --------------------------------------------------------------------------------