Search code examples
c#asynchronouscsvhelper

Proper way to write async using CsvHelper


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(...);

Solution

  • 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.