Skip to content

Instantly share code, notes, and snippets.

@alefcarlos
Created July 6, 2020 11:11
Show Gist options
  • Save alefcarlos/4d14f47afafdaf49ee49fd5ec450d272 to your computer and use it in GitHub Desktop.
Save alefcarlos/4d14f47afafdaf49ee49fd5ec450d272 to your computer and use it in GitHub Desktop.
SockeRingbuffer wip
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