Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1025605
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T11:57:11+00:00 2026-05-16T11:57:11+00:00

What is the best way to build a program that is thread safe in

  • 0

What is the best way to build a program that is thread safe in terms that it needs to write double values to a file. If the function that saves the values via streamwriter is being called by multiple threads? Whats the best way of doing it?


Code from comment:

    static void Main()
    {
        List<double> Values = new List<double>();
        StreamWriter writer = new StreamWriter("test.out");

        for (int i = 0; i < 1000; i++) Values.Add(i);

        foreach (double V in Values)
        {
            ThreadPool.QueueUserWorkItem(delegate(object state) { SaveValues(writer, V); }, V);
        }
    }

    static void SaveValues(StreamWriter writer, double Value)
    {
        lock (writer) writer.WriteLine(Value);
    } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T11:57:12+00:00Added an answer on May 16, 2026 at 11:57 am

    Edit, after decoding the code in your comment

    Your problem is not with locking or threads but with capturing the loop variable. This is a classic problem, all your threads run with a ‘capture’ of the single V variable, and by the time the threads are executed it will have reached its final value of 999. Except maybe for the first few Workitems.

    So, instead of :

    foreach (double V in Values)
    {  
       ThreadPool.QueueUserWorkItem(delegate(object state) 
            { SaveValues(writer, V); }, V); // use of captured V: almost always 999
    }
    

    use

    foreach (double V in Values)
    {
        double W = V;
        ThreadPool.QueueUserWorkItem(delegate(object state)
           { SaveValues(writer, W); }, V);
    }
    

    or, a little more concise,

    foreach (double V in Values)
    {
        double W = V;
        ThreadPool.QueueUserWorkItem((state) => SaveValues(writer, W));
    }
    

    As a variation on @Matti’s answer, it is recommended to lock on a separate simple object. This reduces the risk of anything else locking on the same object (the StreamWriter code itself for instance).

    private StreamWriter writer = ...;         
    private Object writerLock = new Object();  // don't expose through a property 
    // or any other way
    
    lock (writerLock)
    {
        writer.Write(...);
    }
    

    But the way you have set up the SaveValues(StreamWriter writer, ...) method make it a little more complicated. It is better to have an object where writer and writerLock are both private members.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What is the best way to build a loopback URL for an AJAX call?
What's your opinion for the best possible way to build asp.net multilingual localized web
What is the best way to verify/test that a text string is serialized to
i'm trying to build a semi file sharing program, when each computer acts both
For a hobby project I'm going to build a program that when given an
I'm trying to build a small program that hosts vst effects and I would
Whats the best way to go about modifying a C++ program to be used
What is the best way of creating an alphabetically sorted list in Python?
What is the best way to authorize all users to one single page in
What is the best way to store international addresses in a database? Answer in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.