3

Can someone tell me how to use the CsvWriter to write a list of objects without blocking? It's not obvious to me.

Do I need first to call WriteRecords() and after this FlushAsync() or should I write each object one by one using NextRecordAsync()?

Actually, I would expect to use a dedicated method, but it's not there:

public Task WriteRecordsAsync(...);
al-bex
  • 666
  • 1
  • 9
  • 24

1 Answers1

3

WriteRecords will call NextRecord for you, since it's writing multiple. Because of this, you need to write the records manually. It's only a couple more lines.

foreach (var record in records)
{
    csv.WriteRecord(record);
    await csv.NextRecordAsync();
}

The reason there is no WriteRecordsAsync is because it's not required. It would basically be just duplicating most of the code in the library, just to save a few lines. The only part that has low level need for async in the system is writing to the TextWriter, so as little as possible above it is async also.

Josh Close
  • 22,935
  • 13
  • 92
  • 140
  • I don't like the idea to us so many continuations, but maybe it doesn't matter. Would it also be non blocking if I would instead use WriteRecords() and FlushAsync() afterwards? I'm not sure because I haven't diggt deep enough into the source code. I can imagine that at some point a blocking IO operation will be called inside the library if you provide to many records at once. – al-bex May 02 '19 at 11:35
  • @al-bex yes, I occasionally get `InvalidOperationException: The stream is currently in use by a previous operation on the stream.` when using the async version of `NextRecord` – Mark Good Jul 29 '21 at 12:22