AsyncStreamCopier.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace Emby.Server.Implementations.IO
  6. {
  7. public class AsyncStreamCopier : IDisposable
  8. {
  9. // size in bytes of the buffers in the buffer pool
  10. private const int DefaultBufferSize = 4096;
  11. private readonly int _bufferSize;
  12. // number of buffers in the pool
  13. private const int DefaultBufferCount = 4;
  14. private readonly int _bufferCount;
  15. // indexes of the next buffer to read into/write from
  16. private int _nextReadBuffer = -1;
  17. private int _nextWriteBuffer = -1;
  18. // the buffer pool, implemented as an array, and used in a cyclic way
  19. private readonly byte[][] _buffers;
  20. // sizes in bytes of the available (read) data in the buffers
  21. private readonly int[] _sizes;
  22. // the streams...
  23. private Stream _source;
  24. private Stream _target;
  25. private readonly bool _closeStreamsOnEnd;
  26. // number of buffers that are ready to be written
  27. private int _buffersToWrite;
  28. // flag indicating that there is still a read operation to be scheduled
  29. // (source end of stream not reached)
  30. private volatile bool _moreDataToRead;
  31. // the result of the whole operation, returned by BeginCopy()
  32. private AsyncResult _asyncResult;
  33. // any exception that occurs during an async operation
  34. // stored here for rethrow
  35. private Exception _exception;
  36. public TaskCompletionSource<bool> TaskCompletionSource;
  37. private long _bytesToRead;
  38. private long _totalBytesWritten;
  39. private CancellationToken _cancellationToken;
  40. public AsyncStreamCopier(Stream source,
  41. Stream target,
  42. long bytesToRead,
  43. CancellationToken cancellationToken,
  44. bool closeStreamsOnEnd = false,
  45. int bufferSize = DefaultBufferSize,
  46. int bufferCount = DefaultBufferCount)
  47. {
  48. if (source == null)
  49. throw new ArgumentNullException("source");
  50. if (target == null)
  51. throw new ArgumentNullException("target");
  52. if (!source.CanRead)
  53. throw new ArgumentException("Cannot copy from a non-readable stream.");
  54. if (!target.CanWrite)
  55. throw new ArgumentException("Cannot copy to a non-writable stream.");
  56. _source = source;
  57. _target = target;
  58. _moreDataToRead = true;
  59. _closeStreamsOnEnd = closeStreamsOnEnd;
  60. _bufferSize = bufferSize;
  61. _bufferCount = bufferCount;
  62. _buffers = new byte[_bufferCount][];
  63. _sizes = new int[_bufferCount];
  64. _bytesToRead = bytesToRead;
  65. _cancellationToken = cancellationToken;
  66. }
  67. ~AsyncStreamCopier()
  68. {
  69. // ensure any exception cannot be ignored
  70. ThrowExceptionIfNeeded();
  71. }
  72. public static Task CopyStream(Stream source, Stream target, int bufferSize, int bufferCount, CancellationToken cancellationToken)
  73. {
  74. return CopyStream(source, target, 0, bufferSize, bufferCount, cancellationToken);
  75. }
  76. public static Task CopyStream(Stream source, Stream target, long size, int bufferSize, int bufferCount, CancellationToken cancellationToken)
  77. {
  78. var copier = new AsyncStreamCopier(source, target, size, cancellationToken, false, bufferSize, bufferCount);
  79. var taskCompletion = new TaskCompletionSource<bool>();
  80. copier.TaskCompletionSource = taskCompletion;
  81. var result = copier.BeginCopy(StreamCopyCallback, copier);
  82. if (result.CompletedSynchronously)
  83. {
  84. StreamCopyCallback(result);
  85. }
  86. cancellationToken.Register(() => taskCompletion.TrySetCanceled());
  87. return taskCompletion.Task;
  88. }
  89. private static void StreamCopyCallback(IAsyncResult result)
  90. {
  91. var copier = (AsyncStreamCopier)result.AsyncState;
  92. var taskCompletion = copier.TaskCompletionSource;
  93. try
  94. {
  95. copier.EndCopy(result);
  96. taskCompletion.TrySetResult(true);
  97. }
  98. catch (Exception ex)
  99. {
  100. taskCompletion.TrySetException(ex);
  101. }
  102. }
  103. public void Dispose()
  104. {
  105. if (_asyncResult != null)
  106. _asyncResult.Dispose();
  107. if (_closeStreamsOnEnd)
  108. {
  109. if (_source != null)
  110. {
  111. _source.Dispose();
  112. _source = null;
  113. }
  114. if (_target != null)
  115. {
  116. _target.Dispose();
  117. _target = null;
  118. }
  119. }
  120. GC.SuppressFinalize(this);
  121. ThrowExceptionIfNeeded();
  122. }
  123. public IAsyncResult BeginCopy(AsyncCallback callback, object state)
  124. {
  125. // avoid concurrent start of the copy on separate threads
  126. if (Interlocked.CompareExchange(ref _asyncResult, new AsyncResult(callback, state), null) != null)
  127. throw new InvalidOperationException("A copy operation has already been started on this object.");
  128. // allocate buffers
  129. for (int i = 0; i < _bufferCount; i++)
  130. _buffers[i] = new byte[_bufferSize];
  131. // we pass false to BeginRead() to avoid completing the async result
  132. // immediately which would result in invoking the callback
  133. // when the method fails synchronously
  134. BeginRead(false);
  135. // throw exception synchronously if there is one
  136. ThrowExceptionIfNeeded();
  137. return _asyncResult;
  138. }
  139. public void EndCopy(IAsyncResult ar)
  140. {
  141. if (ar != _asyncResult)
  142. throw new InvalidOperationException("Invalid IAsyncResult object.");
  143. if (!_asyncResult.IsCompleted)
  144. _asyncResult.AsyncWaitHandle.WaitOne();
  145. if (_closeStreamsOnEnd)
  146. {
  147. _source.Close();
  148. _source = null;
  149. _target.Close();
  150. _target = null;
  151. }
  152. //_logger.Info("AsyncStreamCopier {0} bytes requested. {1} bytes transferred", _bytesToRead, _totalBytesWritten);
  153. ThrowExceptionIfNeeded();
  154. }
  155. /// <summary>
  156. /// Here we'll throw a pending exception if there is one,
  157. /// and remove it from our instance, so we know it has been consumed.
  158. /// </summary>
  159. private void ThrowExceptionIfNeeded()
  160. {
  161. if (_exception != null)
  162. {
  163. var exception = _exception;
  164. _exception = null;
  165. throw exception;
  166. }
  167. }
  168. private void BeginRead(bool completeOnError = true)
  169. {
  170. if (!_moreDataToRead)
  171. {
  172. return;
  173. }
  174. if (_asyncResult.IsCompleted)
  175. return;
  176. int bufferIndex = Interlocked.Increment(ref _nextReadBuffer) % _bufferCount;
  177. try
  178. {
  179. _source.BeginRead(_buffers[bufferIndex], 0, _bufferSize, EndRead, bufferIndex);
  180. }
  181. catch (Exception exception)
  182. {
  183. _exception = exception;
  184. if (completeOnError)
  185. _asyncResult.Complete(false);
  186. }
  187. }
  188. private void BeginWrite()
  189. {
  190. if (_asyncResult.IsCompleted)
  191. return;
  192. // this method can actually be called concurrently!!
  193. // indeed, let's say we call a BeginWrite, and the thread gets interrupted
  194. // just after making the IO request.
  195. // At that moment, the thread is still in the method. And then the IO request
  196. // ends (extremely fast io, or caching...), EndWrite gets called
  197. // on another thread, and calls BeginWrite again! There we have it!
  198. // That is the reason why an Interlocked is needed here.
  199. int bufferIndex = Interlocked.Increment(ref _nextWriteBuffer) % _bufferCount;
  200. try
  201. {
  202. int bytesToWrite;
  203. if (_bytesToRead > 0)
  204. {
  205. var bytesLeftToWrite = _bytesToRead - _totalBytesWritten;
  206. bytesToWrite = Convert.ToInt32(Math.Min(_sizes[bufferIndex], bytesLeftToWrite));
  207. }
  208. else
  209. {
  210. bytesToWrite = _sizes[bufferIndex];
  211. }
  212. _target.BeginWrite(_buffers[bufferIndex], 0, bytesToWrite, EndWrite, null);
  213. _totalBytesWritten += bytesToWrite;
  214. }
  215. catch (Exception exception)
  216. {
  217. _exception = exception;
  218. _asyncResult.Complete(false);
  219. }
  220. }
  221. private void EndRead(IAsyncResult ar)
  222. {
  223. try
  224. {
  225. int read = _source.EndRead(ar);
  226. _moreDataToRead = read > 0;
  227. var bufferIndex = (int)ar.AsyncState;
  228. _sizes[bufferIndex] = read;
  229. }
  230. catch (Exception exception)
  231. {
  232. _exception = exception;
  233. _asyncResult.Complete(false);
  234. return;
  235. }
  236. if (_moreDataToRead && !_cancellationToken.IsCancellationRequested)
  237. {
  238. int usedBuffers = Interlocked.Increment(ref _buffersToWrite);
  239. // if we incremented from zero to one, then it means we just
  240. // added the single buffer to write, so a writer could not
  241. // be busy, and we have to schedule one.
  242. if (usedBuffers == 1)
  243. BeginWrite();
  244. // test if there is at least a free buffer, and schedule
  245. // a read, as we have read some data
  246. if (usedBuffers < _bufferCount)
  247. BeginRead();
  248. }
  249. else
  250. {
  251. // we did not add a buffer, because no data was read, and
  252. // there is no buffer left to write so this is the end...
  253. if (Thread.VolatileRead(ref _buffersToWrite) == 0)
  254. {
  255. _asyncResult.Complete(false);
  256. }
  257. }
  258. }
  259. private void EndWrite(IAsyncResult ar)
  260. {
  261. try
  262. {
  263. _target.EndWrite(ar);
  264. }
  265. catch (Exception exception)
  266. {
  267. _exception = exception;
  268. _asyncResult.Complete(false);
  269. return;
  270. }
  271. int buffersLeftToWrite = Interlocked.Decrement(ref _buffersToWrite);
  272. // no reader could be active if all buffers were full of data waiting to be written
  273. bool noReaderIsBusy = buffersLeftToWrite == _bufferCount - 1;
  274. // note that it is possible that both a reader and
  275. // a writer see the end of the copy and call Complete
  276. // on the _asyncResult object. That race condition is handled by
  277. // Complete that ensures it is only executed fully once.
  278. long bytesLeftToWrite;
  279. if (_bytesToRead > 0)
  280. {
  281. bytesLeftToWrite = _bytesToRead - _totalBytesWritten;
  282. }
  283. else
  284. {
  285. bytesLeftToWrite = 1;
  286. }
  287. if (!_moreDataToRead || bytesLeftToWrite <= 0 || _cancellationToken.IsCancellationRequested)
  288. {
  289. // at this point we know no reader can schedule a read or write
  290. if (Thread.VolatileRead(ref _buffersToWrite) == 0)
  291. {
  292. // nothing left to write, so it is the end
  293. _asyncResult.Complete(false);
  294. return;
  295. }
  296. }
  297. else
  298. // here, we know we have something left to read,
  299. // so schedule a read if no read is busy
  300. if (noReaderIsBusy)
  301. BeginRead();
  302. // also schedule a write if we are sure we did not write the last buffer
  303. // note that if buffersLeftToWrite is zero and a reader has put another
  304. // buffer to write between the time we decremented _buffersToWrite
  305. // and now, that reader will also schedule another write,
  306. // as it will increment _buffersToWrite from zero to one
  307. if (buffersLeftToWrite > 0)
  308. BeginWrite();
  309. }
  310. }
  311. internal class AsyncResult : IAsyncResult, IDisposable
  312. {
  313. // Fields set at construction which never change while
  314. // operation is pending
  315. private readonly AsyncCallback _asyncCallback;
  316. private readonly object _asyncState;
  317. // Fields set at construction which do change after
  318. // operation completes
  319. private const int StatePending = 0;
  320. private const int StateCompletedSynchronously = 1;
  321. private const int StateCompletedAsynchronously = 2;
  322. private int _completedState = StatePending;
  323. // Field that may or may not get set depending on usage
  324. private ManualResetEvent _waitHandle;
  325. internal AsyncResult(
  326. AsyncCallback asyncCallback,
  327. object state)
  328. {
  329. _asyncCallback = asyncCallback;
  330. _asyncState = state;
  331. }
  332. internal bool Complete(bool completedSynchronously)
  333. {
  334. bool result = false;
  335. // The _completedState field MUST be set prior calling the callback
  336. int prevState = Interlocked.CompareExchange(ref _completedState,
  337. completedSynchronously ? StateCompletedSynchronously :
  338. StateCompletedAsynchronously, StatePending);
  339. if (prevState == StatePending)
  340. {
  341. // If the event exists, set it
  342. if (_waitHandle != null)
  343. _waitHandle.Set();
  344. if (_asyncCallback != null)
  345. _asyncCallback(this);
  346. result = true;
  347. }
  348. return result;
  349. }
  350. #region Implementation of IAsyncResult
  351. public Object AsyncState { get { return _asyncState; } }
  352. public bool CompletedSynchronously
  353. {
  354. get
  355. {
  356. return Thread.VolatileRead(ref _completedState) ==
  357. StateCompletedSynchronously;
  358. }
  359. }
  360. public WaitHandle AsyncWaitHandle
  361. {
  362. get
  363. {
  364. if (_waitHandle == null)
  365. {
  366. bool done = IsCompleted;
  367. var mre = new ManualResetEvent(done);
  368. if (Interlocked.CompareExchange(ref _waitHandle,
  369. mre, null) != null)
  370. {
  371. // Another thread created this object's event; dispose
  372. // the event we just created
  373. mre.Close();
  374. }
  375. else
  376. {
  377. if (!done && IsCompleted)
  378. {
  379. // If the operation wasn't done when we created
  380. // the event but now it is done, set the event
  381. _waitHandle.Set();
  382. }
  383. }
  384. }
  385. return _waitHandle;
  386. }
  387. }
  388. public bool IsCompleted
  389. {
  390. get
  391. {
  392. return Thread.VolatileRead(ref _completedState) !=
  393. StatePending;
  394. }
  395. }
  396. #endregion
  397. public void Dispose()
  398. {
  399. if (_waitHandle != null)
  400. {
  401. _waitHandle.Dispose();
  402. _waitHandle = null;
  403. }
  404. }
  405. }
  406. }