/// <summary> /// 写入文件,可不等待 /// </summary> /// <param name="fileStartPoint">从文件的哪里开始写</param> /// <param name="data">写入的数据</param> /// <param name="dataOffset"></param> /// <param name="dataLength"></param> public async Task WriteAsync(long fileStartPoint, byte[] data, int dataOffset, int dataLength) { var task = new TaskCompletionSource <bool>(); var fileSegment = new FileSegment(fileStartPoint, data, dataOffset, dataLength, task); FileSegmentList.Enqueue(fileSegment); await task.Task; }
private async Task WriteToFile() { while (true) { _isWriting = true; var fileSegment = await FileSegmentList.DequeueAsync(); try { Stream.Seek(fileSegment.FileStartPoint, SeekOrigin.Begin); await Stream.WriteAsync(fileSegment.Data, fileSegment.DataOffset, fileSegment.DataLength); } catch (Exception e) { Exception = e; WriteFinished?.Invoke(this, EventArgs.Empty); return; } _isWriting = false; try { fileSegment.TaskCompletionSource?.SetResult(true); StepWriteFinished ( this, new StepWriteFinishedArgs ( fileSegment.FileStartPoint, fileSegment.DataOffset, fileSegment.Data, fileSegment.DataLength ) ); } catch (Exception) { // 执行业务代码 } var isEmpty = FileSegmentList.Count == 0; if (isEmpty) { WriteFinished?.Invoke(this, EventArgs.Empty); if (_isDispose) { return; } } } }
/// <summary> /// 加入写文件队列 /// </summary> public void QueueWrite(long fileStartPoint, byte[] data, int dataOffset, int dataLength) { var fileSegment = new FileSegment(fileStartPoint, data, dataOffset, dataLength); FileSegmentList.Enqueue(fileSegment); }