我有一个像这样的 wcf 方法来上传文件 block :
public void UploadChunk ( RemoteFileChunk file )
{
using ( var targetStream = new FileStream("some-path", FileMode.OpenOrCreate, FileAccess.Append, FileShare.None) )
{
file.Stream.CopyTo(targetStream);
file.Stream.Close();
}
}
这是非常基本的东西。但是在异常(exception)情况下发生的事情非常奇怪。异常(exception)情况步骤:
- 开始上传 block
- 上传过程中互联网连接松动
- UploadChunk 方法因失去互联网连接而抛出
CommunicationException
- ...等待互联网连接恢复
- 再次开始上传最后一 block
- 砰!!!抛出以下异常:
The process cannot access the file 'some-path' because it is being used by another process.
我知道该文件没有被其他任何人触及,这让我知道该文件在连接丢失时的最后一次调用中保持打开状态。但据我所知,using
语句应该关闭 FileStream
,但在本例中它没有。
我可能在这里遗漏了什么?
顺便说一句,我还有一个 question我猜这是由我不知道的相同问题引起的。也许它可以引导你们找到一些线索。
最佳答案
什么是 RemoteFileChunk?我的猜测是打开文件的是 RemoteFileChunk。您没有显示 RemoteFileChunk 的任何代码,这些代码表明它会在发生异常时自动关闭其 Stream 。这应该可行(尽管将关闭封装在 RemoteFileChunk 本身中可能更好):
public void UploadChunk ( RemoteFileChunk file )
{
using ( var targetStream = new FileStream("some-path", FileMode.OpenOrCreate, FileAccess.Append, FileShare.None) )
{
try
{
file.Stream.CopyTo(targetStream);
}
finally
{
file.Stream.Close();
}
}
}
关于c# - 即使在 using 语句中,FileStream 也不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078304/