public BufferedChunkWriter(Fiber fiber, Scheduler scheduler, ChunkWriter output, int bufferLengthInBytes) { _waitAfterMinFlush = 10.Milliseconds(); _fiber = fiber; _scheduler = scheduler; _output = output; _inputBuffer = new Chunk(bufferLengthInBytes); _outputBuffer = new Chunk(bufferLengthInBytes); _minFlushLength = bufferLengthInBytes/2; }
void FlushBuffer() { TimeSpan sleepInterval = TimeSpan.Zero; try { lock (_lock) { while (_running && _inputBuffer.Length == 0) Monitor.Wait(_lock); if (!_running) return; Chunk swap = _outputBuffer; _outputBuffer = _inputBuffer; _inputBuffer = swap; Monitor.PulseAll(_lock); } ArraySegment<byte> content = _outputBuffer.Content; if (content.Count > 0) { _output.Write(content, _outputBuffer.NotifyUnsent); _outputBuffer.Reset(); _blockCount++; _byteCount += content.Count; if (content.Count < _minFlushLength) sleepInterval = _waitAfterMinFlush; } } finally { if (_running) { if (sleepInterval != TimeSpan.Zero) _scheduler.Schedule(sleepInterval, _fiber, FlushBuffer); else _fiber.Add(FlushBuffer); } } }