Link to home
Start Free TrialLog in
Avatar of fantasylan
fantasylan

asked on

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.
Avatar of no worries :-) no nothing
no worries :-) no nothing
Flag of Greece image


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....;
}
You can also use:

Thread.Sleep (500);                     //  500 milliseconds
Avatar of fantasylan
fantasylan

ASKER

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,
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.