0

I have two applications. The server send files to my clients. The clients are implemented in Unity3d with C#. Each client has one thread to receive files from server. If I send the files over the network, I write the bytes to the file with this code:

private Thread clientThread;
private object writeLock = new object();

public void StartConnection()
{
   // Start connection to server.
   clientThread = new Thread(GetFiles);
}
public void GetFiles()
{
    string fullPath;
    // Receive bytes from server

    fullPath = Path.Combine(clientDirPath, fileNameFromServer);
    lock(writeLock)
    {
      using (BinaryWriter bWrite = new BinaryWriter(File.Open(fullPath, FileMode.Create)))
      {
          bWrite.Write(binaryFileContent);
          bWrite.Flush();
      }
}

Now, if I start multple clients and send files to receive them synchronously on the client-side, I get this error message: System.IO.IOException:Sharing violation on path. Whether I use the lock-statement it is not working. Do anyone know the way to get it working?

EDIT: I added more code.

Tenshi
  • 75
  • 2
  • 12
  • 3
    Lock only works in the same process, if you want to lock with multiple processes, you need to use a semaphore. If this is a single process, are you creating the `writelock` globally, that it is shared across thread instances? – Ron Beyer Oct 30 '15 at 18:34
  • also after you write to the file you should issue an immediate `bWrite.Flush();` – MethodMan Oct 30 '15 at 18:37
  • @Ron Beyer Thanks for the really fast answer! The problem with semaphore is, that I have to limit the number of threads, so there is no constructor without arguments or did I miss something? My problem is, that I don't know the number of clients before. – Tenshi Oct 30 '15 at 18:52
  • You haven't really defined it though, is the code above in a client, or is it in a single server process? Do the clients run on the same machine? – Ron Beyer Oct 30 '15 at 18:54
  • @MethodMan Thanks! However, if I use `using` I don't need to flush. Source: http://stackoverflow.com/questions/7710661/do-you-need-to-call-flush-on-a-stream-if-you-are-using-the-using-statement – Tenshi Oct 30 '15 at 18:57
  • @Ron Beyer The above code is in the client class and yes the clients run on the same machine. The server only sends the files to the clients and the client do the rest. Yes the `writeLock` is a global variable and the rest of the code is in a method that received the files from server. – Tenshi Oct 30 '15 at 18:59
  • if you want to insure the contents are written write away yes you do. – MethodMan Oct 30 '15 at 18:59
  • @MethodMan Thanks, I added flush now, but the problem remains. – Tenshi Oct 30 '15 at 19:29

0 Answers0