次のコードを取得しました(マルチスレッド環境ではうまく機能しません)
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.
}
}
現在実行中のジョブがない場合、Sendメソッドはジョブを非同期的に呼び出す必要があります。ある場合は、ジョブをキューに入れる必要があります。
割り当て/チェックの周りにロックをかける_currentJob
と、すべてが正常に機能します。しかし、それを解決するためのロックフリーの方法はありますか?
アップデート
私はソケットを使用していて、それSendAsync
が情報を送信する方法です。つまり、Send()
メソッドが呼び出されたときに、書き込み/ジョブが保留されているかどうかがわかりません。