0

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;
                     }}
2
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by alaa sam
1

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;
    }
  }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.