예제 #1
0
        /// <summary>
        /// 关闭写入流, 并引发可能的最后一次通知事件.
        /// </summary>
        public void Close()
        {
            try
            {
                if (csvStream != null)
                {
                    csvStream.Close();

                    if (dataHandler != null)
                    {
                        //如果记录总数等于通知设定总数, 说明写入结束时刚好是要通知的数量, 但在 WriteLineAsync 方法中已经通知, 所以在这不再通知.
                        if (TotalRowCount != WriteProgressSize)
                        {
                            CsvWriteProgressInfo info = new CsvWriteProgressInfo();
                            info.CurrentRowCount = TotalRowCount % WriteProgressSize;
                            info.WirteRowCount   = TotalRowCount;
                            dataHandler.Invoke(info);
                        }
                    }
                }
            }
            finally
            {
                csvStream = null;
            }
        }
예제 #2
0
        /// <summary>
        /// 异步写入单行数据, 可多次执行, 之后执行 Close 方法关闭写入流.
        /// </summary>
        /// <param name="rowData">一行数据,由字段集合组成.</param>
        /// <returns>Task</returns>
        public async Task WriteLineAsync(List <string> rowData)
        {
            if (CancelToken.IsCancellationRequested)
            {
                CancelToken.ThrowIfCancellationRequested();
            }

            if (rowData == null)
            {
                throw new ArgumentNullException(nameof(rowData));
            }

            //如果写入过一条数据, 则字段数固定. 如果再次写入的字段数不同, 报异常.
            if (columnCount > 0 && columnCount != rowData.Count)
            {
                throw new ArgumentException("the rowData count must be equal to " + columnCount.ToString());
            }

            await csvStream.WriteLineAsync(SerializeRow( rowData ));

            TotalRowCount++;

            //设置字段数
            if (columnCount == 0)
            {
                columnCount = rowData.Count;
            }

            //发送通知
            if (dataHandler != null)
            {
                //如果取余数=0, 发送通知.
                if (TotalRowCount % WriteProgressSize == 0L)
                {
                    CsvWriteProgressInfo info = new CsvWriteProgressInfo();
                    info.CurrentRowCount = WriteProgressSize;
                    info.WirteRowCount   = TotalRowCount;
                    dataHandler.Invoke(info);
                }
            }
        }