/// <summary> /// 异步写入单行数据, 可多次执行, 之后执行 Close 方法关闭写入流. /// </summary> /// <typeparam name="T">要写入的数据对象类型</typeparam> /// <param name="rowData">要写入的数据对象实例</param> /// <param name="expression">处理对象实例,返回字段集合的方法.</param> /// <returns>Task</returns> public async Task WriteLineAsync <T>(T rowData, Func <T, List <string> > expression) where T : new() { if (this.CancelToken.IsCancellationRequested) { this.CancelToken.ThrowIfCancellationRequested(); } if (rowData == null) { throw new ArgumentNullException("rowData"); } if (expression == null) { throw new ArgumentNullException("expression"); } //取转换后的行数据 var row = expression.Invoke(rowData); //如果写入过一条数据, 则字段数固定. 如果再次写入的字段数不同, 报异常. if (this.ColumnCount > 0 && this.ColumnCount != row.Count) { throw new ArgumentException("the rowData count must be equal to " + ColumnCount.ToString()); } List <string> rows = this.SerializeRows(row); await this.CsvStream.WriteLineAsync(rows[0]); this.TotalRowCount++; //设置字段数 if (this.ColumnCount == 0) { this.ColumnCount = row.Count; } //发送通知 if (Progress != null) { //如果取余数=0, 发送通知. if (TotalRowCount % this.WriteProgressSize == 0L) { CsvWriteProgressInfo info = new CsvHelperAsync.CsvWriteProgressInfo(); info.CurrentRowCount = this.WriteProgressSize; info.WirteRowCount = this.TotalRowCount; Progress.Report(info); } } }
/// <summary> /// 关闭写入流, 并引发可能的最后一次通知事件. /// </summary> public void Close() { if (this.CsvStream != null) { this.CsvStream.Close(); this.CsvStream = null; if (Progress != null) { //如果记录总数等于通知设定总数, 说明写入结束时刚好是要通知的数量, 但在 WriteLineAsync 方法中已经通知, 所以在这不再通知. if (TotalRowCount != WriteProgressSize) { CsvWriteProgressInfo info = new CsvHelperAsync.CsvWriteProgressInfo(); info.CurrentRowCount = this.TotalRowCount % this.WriteProgressSize; info.WirteRowCount = this.TotalRowCount; Progress.Report(info); } } } }