• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 263
  • Last Modified:

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?

Regards.
0
fantasylan
Asked:
fantasylan
  • 2
  • 2
  • 2
1 Solution
 
George K.Commented:

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

Thread.Sleep (500);                     //  500 milliseconds
0
 
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,
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
wdosanjosCommented:
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

0
 
fantasylanAuthor Commented:
Hi wdosanjos

How do I indicate to the other waiting threads?
0
 
wdosanjosCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now