Created
July 6, 2020 11:11
-
-
Save alefcarlos/4d14f47afafdaf49ee49fd5ec450d272 to your computer and use it in GitHub Desktop.
SockeRingbuffer wip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Oragon.Common.RingBuffer.Specialized | |
{ | |
public class SocketRingBuffer : DisposableRingBuffer<Socket> | |
{ | |
public SocketRingBuffer(int capacity, Func<Socket> bufferFactory) : base(capacity, bufferFactory) | |
{ | |
} | |
public override IAccquisitonController<Socket> Accquire() => new ScoketAccquisitonController(this.availableBuffer, this.WaitTime, this.itemFactoryFunc); | |
internal class ScoketAccquisitonController : IAccquisitonController<Socket> | |
{ | |
private readonly ConcurrentQueue<Socket> availableBuffer; | |
internal ScoketAccquisitonController(ConcurrentQueue<Socket> availableBuffer, TimeSpan waitTime, Func<Socket> factory) | |
{ | |
this.availableBuffer = availableBuffer; | |
Socket tmpBufferElement; | |
while (this.availableBuffer.TryDequeue(out tmpBufferElement) == false) | |
{ | |
Thread.Sleep(waitTime); | |
} | |
if (!IsSocketConnected(tmpBufferElement)) | |
tmpBufferElement = factory(); | |
this.Current = tmpBufferElement; | |
} | |
static bool IsSocketConnected(Socket s) | |
{ | |
return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected); | |
} | |
public Socket Current { get; } | |
public void Dispose() | |
{ | |
this.availableBuffer.Enqueue(this.Current); | |
GC.SuppressFinalize(this); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment