I got the following code (which doesn't work very well in a multi threaded environment)
public class SomeClass
{
private readonly ConcurrentQueue<ISocketWriterJob> _writeQueue = new ConcurrentQueue<ISocketWriterJob>();
private ISocketWriterJob _currentJob;
public void Send(ISocketWriterJob job)
{
if (_currentJob != null)
{
_writeQueue.Enqueue(job);
return;
}
_currentJob = job;
_currentJob.Write(_writeArgs);
// The job is invoked asynchronously here
}
private void HandleWriteCompleted(SocketError error, int bytesTransferred)
{
// error checks etc removed for this sample.
if (_currentJob.WriteCompleted(bytesTransferred))
{
_currentJob.Dispose();
if (!_writeQueue.TryDequeue(out _currentJob))
{
_currentJob = null;
return;
}
}
_currentJob.Write(_writeArgs);
// the job is invoked asycnhronously here.
}
}
The Send method should invoke the job asynchronously if there isn't a current job being executed. It should enqueue the job if there is.
Putting a lock around the _currentJob
assignment/check would make everything work just fine. But are there a lock free way to solve it?
Update
I'm using a socket and it's SendAsync
method to send the information. Which means that I do not know if there is a write/job pending or not when the Send()
method is invoked.