How to generate threads simultaneously to write to a file in an exclusive manner

Hello Experts,

I am writing a multi-threaded application which generates 10 threads simultaneously and then calls a method to write to a file in an exclusive manner i.e. One thread at a time. How do I do this?
Can I use ThreadPool to do this? If so, how do I go about implementing this?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

George K.Commented:

You can wait for another thread to end with Join method:
static void Main()
  Thread myt = new Thread (executecode);
  Console.WriteLine ("thread myt is finished");
static void executecode()
 ... do someting here....;
George K.Commented:
You can also use:

Thread.Sleep (500);                     //  500 milliseconds
fantasylanAuthor Commented:
Hi georgekl,

I am generating these threads simultaneously.
I think join is more reliable and faster than using sleep but this doesnt solve my problem,
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

The 'Thread' class should work fine and you need to synchronize your file writing method, so that only one thread writes to the file at any given time.  Something like this:

private File _myFile = new File();

public void WriteMyFile()
    lock (_myFile)
        // Write to your file (only one thread at a time).
        // Other threads will wait on the 'lock' until the block is completed

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
fantasylanAuthor Commented:
Hi wdosanjos

How do I indicate to the other waiting threads?
You don't need to indicate to them, they'll automatic wait on the 'lock' once they hit it and another thread is already in the 'lock' block.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.