我有一個用於將文件下載到客戶端的asmx web服務。如下所示我的下載方法:Web服務中文件下載中的多線程併發問題
[WebMethod]
public byte[] DownloadFile(int id)
{
lock (this)
{
if (id == 0)
{
throw new ArgumentException("Input value is not valid");
}
IGWFileRepository fileRepository = new GWFileRepository();
GWFile file = fileRepository.GetFileById(id);
string path = Server.MapPath(RepositoryDir + "/" + file.DiscName);
BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read));
reader.BaseStream.Position = 0;
byte[] content = reader.ReadBytes(Convert.ToInt32(reader.BaseStream.Length));
reader.Close();
return content;
}
}
我的問題是,當我有100個用戶同時下載強調它,我得到一個異常:
Exception: System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.IO.IOException: The process cannot access the file 'C:\Subversion\Repository\cb0a27e2-2d23-43b1-a12e-f07fb401cfc9.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.Open(String path, FileMode mode, FileAccess access)
at GrenWebRepository.RepositoryService.DownloadFile(Int32 id) in C:\Subversion\Repository\RepositoryService.asmx.cs:line 62
--- End of inner exception stack trace ---
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at RepositoryTester.RS.RepositoryService.DownloadFile(Int32 id) in C:\Subversion\Repository\Web References\RS\Reference.cs:line 174
at RepositoryTester.User.DownloadAction() in C:\Subversion\Repository\RepositoryTester\RepositoryTester\User.cs:line 110
(文件名稱被遮擋)
任何一個知道如何解決這個併發問題,我的鎖不正確?
其他進程是否有可能更新該.jpg文件?在相關說明中,您不需要'BinaryReader',因爲您可以直接從'FileStream'中讀取。或者,想一想,你可以調用'File.ReadAllBytes'。 – 2011-05-02 17:31:05
關於鎖,通常不是一個好主意(做)鎖,這將是更好的有一個私人鎖定令牌鎖定,因爲這確保鎖不能在課堂以外。 – rasmusvhansen 2011-05-02 17:34:53