hey
I'm writing a multithreaded server , and I want to print a line in a file whenever a client is connected , I need to lock the filestream to prevent the lines of multiple thread from overlapping I used an integer lock but it won't work right , so any help

 if (server.Pending())
             {

                 TcpClient client = server.AcceptTcpClient();
                 string time;
                 time = DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt");
                 if (Lock == 0)
                 {
                     Lock = 1;
                     if (first == 0)
                     {

                         first++;
                     }
                     else
                     {
                         statistics = new FileStream("statistic.txt", FileMode.Append, FileAccess.Write, FileShare.None);
                         wr = new BinaryWriter(statistics);
                     }
                     string clientIPAddress =time+ ", A connection is made from the client whose IP Address is: " + IPAddress.Parse(((
                     IPEndPoint)client.Client.RemoteEndPoint).Address.ToString())+"\r\n";
                     wr.Write(clientIPAddress);
                     closeFile();


                     Console.Write(clientIPAddress);

                     Lock = 0;
                     }}

Recommended Answers

All 2 Replies

You can use the lock keyword for this. The basic idea is that you lock a private constant object whenever you read or write from the shared variable. Like this:

public class MyMultiThread
{
  private const Object lockObject = new Object();
  private int sharedVariable;

  public MyMultiThread()
  {
    WriteSharedVariable(0);
  }

  public void WriteSharedVariable(int aValue)
  {
    lock(lockObject)
    {
      sharedVariable = aValue;
    }
  }

  public int ReadSharedVariable()
  {
    lock(lockObject)
    {
      return sharedVariable;
    }
  }
}

Thanks a lot for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.