DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Redirects With Cloudflare Bulk Redirects
  • How to Convert Excel and CSV Documents to HTML in Java
  • Datafaker 2.0
  • Serverless Extraction and Processing of CSV Content From a Zip File With Zero Coding

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Streamlining Event Data in Event-Driven Ansible
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems

Writing to a CSV File From Multiple Threads

We look at how to write metadata to CSV files from multiple threads in parallel using concurrent queues.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Apr. 25, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
33.7K Views

Join the DZone community and get the full member experience.

Join For Free

I was writing document and metadata exporter that reads data from SharePoint and writes it to multiple files. I needed to boost up performance of my exporter and I went with multiple threads pumping out the data from SharePoint. One problem I faced — writing metadata to CSV files from multiple threads in parallel. This blog post shows how to do it using concurrent queues.

This posting uses CsvHelper library to write objects to CSV-files. Last time I covered this library in my blog post Generating CSV-files on .NET.

Problem: Writing to a File From Multiple Threads

I have multiple threads that traverse a document library on SharePoint and I need to generate some reports on the fly. I have no option to add data to some buffer and flush it to files at the end of the project as the server memory is limited.

What I need is some thread-safe list I can read from another thread and where worker threads can add their DTOs.

I had some considerations:

  • I don't want to bind the code too tight to some logging framework that can do the job.
  • I need some point in the code where I can control the reading and writing of data.
  • Instead of primitive custom code with thread locking I prefer something provided by a framework.

With these ideas in mind I started building my solution.

Using ConcurrentQueue<T>

I solved the problem using ConcurrentQueue<T>. Threads that gather data from the SharePoint document library add Data Transfer Objects (DTOs) to a concurrent queue. Now I don't have to worry about threading issues, which is why concurrent queues were created. I also added a thread that reads from a concurrent queue and writes DTOs to a CSV file.

I wrote an example console application to illustrate my solution. It's easy to try out. Sorry for messy code.

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
}
 
class Program
{
    private static ConcurrentQueue<Product> _products = new ConcurrentQueue<Product>();
 
    static void Main(string[] args)
    {
        var source = new CancellationTokenSource();
        var token = source.Token;           
 
        Task.Run(() => {
            var conf = new Configuration();
            conf.Encoding = Encoding.UTF8;
            conf.CultureInfo = CultureInfo.InvariantCulture;
 
            using (var stream = File.OpenWrite("products.txt"))
            using (var streamWriter = new StreamWriter(stream))
            using (var writer = new CsvWriter(streamWriter, conf))
            {
                writer.WriteHeader<Product>();
                writer.NextRecord();
 
                while (true)
                {
                    if(token.IsCancellationRequested)
                    {
                        streamWriter.Flush();
                        return;
                    }
 
                    Product product = null;
 
                    while(_products.TryDequeue(out product))
                    {
                        writer.WriteRecord(product);
                        writer.NextRecord();
                    }
                }
            }
        }, token);
 
        var task1 = Task.Run(() => 
        {
            foreach(var number in Enumerable.Range(1, 10))
            {
                var product = new Product
                {
                    Id = number,
                    Name = "Product " + number,
                    Price = Math.Round((10d * number) / DateTime.Now.Second, 2)
                };
 
                _products.Enqueue(product);
 
                Task.Delay(150).Wait();
            }
        });
 
        var task2 = Task.Run(() => 
        {
            foreach (var number in Enumerable.Range(11, 10))
            {
                var product = new Product
                {
                    Id = number,
                    Name = "Product " + number,
                    Price = Math.Round((10d * number) / DateTime.Now.Second, 2)
                };
 
                _products.Enqueue(product);
 
                Task.Delay(150).Wait();
            }
        });
 
        Task.WaitAll(task1, task2);            
 
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Press any key to exit ...");
        Console.ReadKey();
 
        source.Cancel();
    }
}

This code does its job well in my case. Here's the CSV file with the product information.

CSV File

Although I went with default settings it's easy to configure CsvWriter to use the settings one needs.

What if SpinWait Is too Agressive?

Some of my dear readers might point out one thing — isn't a concurrent queue reading too aggressive? Well, there's no better answer than the usual "it depends." Internally, ConcurrentQueue<T> uses SpinWait and this should be enough in my case. Still, when it runs empty it consumes 25% of CPU. SpinWait is okay when items are added to the queue frequently.

If SpinWait in the concurrent queue is too agressive then it's possible to calm it down a little bit when the queue is empty. I added a 500 millisecond delay.

Task.Run(async () => {
    var conf = new Configuration();
    conf.Encoding = Encoding.UTF8;
    conf.CultureInfo = CultureInfo.InvariantCulture;
 
    using (var stream = File.OpenWrite("products.txt"))
    using (var streamWriter = new StreamWriter(stream))
    using (var writer = new CsvWriter(streamWriter, conf))
    {
        writer.WriteHeader<Product>();
        writer.NextRecord();
 
        while (true)
        {
            if(token.IsCancellationRequested)
            {
                streamWriter.Flush();
                return;
            }
 
            Product product = null;
 
            while(_products.TryDequeue(out product))
            {
                writer.WriteRecord(product);
                writer.NextRecord();
            }
 
            // No data, let's delay
            await Task.Delay(500);
        }
    }
}, token);

In my case. this calmed the concurrent queue reading down. Instead on 25% of tge CPU it stays near 3% when the concurrent queue is empty.

Wrapping Up

Instead of inventing custom mechanisms to handle concurrent writes to a file from multiple threads we can use already existing classes and components. CsvHelper is great library with excellent performance. The ConcurrentQueue<T> class helped us to take control of file writing to tune the CPU usage during data exports. In the end we have simple and easy to extend solution we can also use in other projects.

CSV

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Redirects With Cloudflare Bulk Redirects
  • How to Convert Excel and CSV Documents to HTML in Java
  • Datafaker 2.0
  • Serverless Extraction and Processing of CSV Content From a Zip File With Zero Coding

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!