我有一個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());
}
}
你是如何讀/文件發送到客戶端?請顯示一些代碼。 – 2011-02-25 13:38:08
Sory,這裏是服務器端功能和客戶端功能。 – 2011-02-25 14:10:21