2011-02-25 44 views
1

我有一個WCF服務,使客戶端下載一些文件併發數據流。儘管每個客戶端的請求都有一個新的服務實例,但如果兩個客戶端嘗試同時下載同一個文件,則首先到達的請求會鎖定該文件直到完成該文件。所以另一個客戶端實際上是在等待第一個客戶端完成,因爲沒有多個服務。必須有辦法避免這種情況。我可以有一個物理文件

是否有任何人誰知道我怎樣才能避免這種情況,而無需在服務器上的硬盤多份文件?還是我在做一些完全錯誤的事情?

這是服務器端代碼:

`公共流DownloadFile(字符串路徑) { System.IO.FileInfo的fileInfo =新System.IO.FileInfo(路徑);

 // check if exists 
     if (!fileInfo.Exists) throw new FileNotFoundException(); 

     // open stream 
     System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); 

     // return result 
     return stream; 
    }` 

這是客戶端代碼:

public void Download(string serverPath, string path) 
    { 
     Stream stream; 
     try 
     { 
      if (System.IO.File.Exists(path)) System.IO.File.Delete(path); 
      serviceStreamed = new ServiceStreamedClient("NetTcpBinding_IServiceStreamed"); 
      SimpleResult<long> res = serviceStreamed.ReturnFileSize(serverPath); 
      if (!res.Success) 
      { 
       throw new Exception("File not found: \n" + serverPath); 
      } 
      // get stream from server 
      stream = serviceStreamed.DownloadFile(serverPath); 

       // write server stream to disk 
       using (System.IO.FileStream writeStream = new System.IO.FileStream(path, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)) 
       { 
        int chunkSize = 1 * 48 * 1024; 
        byte[] buffer = new byte[chunkSize]; 
        OnTransferStart(new TransferStartArgs()); 
        do 
        { 
         // read bytes from input stream 
         int bytesRead = stream.Read(buffer, 0, chunkSize); 
         if (bytesRead == 0) break; 


         // write bytes to output stream 
         writeStream.Write(buffer, 0, bytesRead); 


         // report progress from time to time 
         OnProgressChanged(new ProgressChangedArgs(writeStream.Position)); 
        } while (true); 

        writeStream.Close(); 
        stream.Dispose(); 



       } 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      if (serviceStreamed.State == System.ServiceModel.CommunicationState.Opened) 
      { 
       serviceStreamed.Close(); 
      } 
      OnTransferFinished(new TransferFinishedArgs()); 
     } 
    } 
+1

你是如何讀/文件發送到客戶端?請顯示一些代碼。 – 2011-02-25 13:38:08

+0

Sory,這裏是服務器端功能和客戶端功能。 – 2011-02-25 14:10:21

回答

0

我Kjörling先生的意見,這是很難幫助沒有看到你在做什麼。既然你只是從你的服務器下載文件,爲什麼你打開它作爲R/W(導致鎖)。如果以只讀方式打開它,則不會鎖定。如果我的建議缺乏,請不要模糊,因爲這只是我對問題的解釋而沒有大量的信息。

+0

我添加了代碼。我不明白,我是如何將其打開爲只讀的?我已經將FileAccess設置爲Read,是不是你在說什麼?或者還有什麼我必須做的? – 2011-02-25 14:09:03

+1

這不一定是導致鎖定的'FileAccess',請檢查'FileShare',FileStream可用的第三個參數。 – 2011-02-25 14:22:20

0

試試這個,它應該使兩個線程同時並且獨立的讀取文件:

System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); 
+0

好吧,我會嘗試使用FileShare,只是我現在無法嘗試。這將不得不等到我明天去我的辦公室......我會檢查答案,如果它的工作。 – 2011-02-25 14:51:41

相關問題