我正在使用RestSharp实现一个简单的文件上传桌面工具。当我使用自定义流编写器向请求添加大文件(以将更新上载进度更新为gui)时,stream.Write
会抛出OutOfMemoryException。简化的代码示例:
...
var request = new RestRequest { Resource = "/test" };
request.Method = Method.POST;
request.AddFile("file", writer, "largefile.iso");
var response = client.Execute(request);
...
private void writer(Stream stream)
{
using (FileStream reader = File.OpenRead("d:\\download\\largefile.iso"))
{
byte[] buffer = new byte[16384]; //16k buffer
int bytesRead = 0;
int read = 0;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, read);
bytesRead += read;
System.Diagnostics.Debug.WriteLine("uploading: " + (int) ((double)bytesRead / reader.Length * 100) + "%");
}
reader.Close();
}
}
这适用于小文件,但Stream写入泄漏内存,最终崩溃。这里有什么我想念的吗?
答案 0 :(得分:0)
也许你应该在每次写入后尝试刷新流缓冲区:
private void writer(Stream stream)
{
using (FileStream reader = File.OpenRead("d:\\download\\largefile.iso"))
{
byte[] buffer = new byte[16384]; //16k buffer
int bytesRead = 0;
int read = 0;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, read);
stream.Flush();
bytesRead += read;
System.Diagnostics.Debug.WriteLine("uploading: " + (int)((double)bytesRead / reader.Length * 100) + "%");
}
reader.Close();
}
}
答案 1 :(得分:0)
在挖掘RestSharp源代码后自己解决了这个问题。 http://support.microsoft.com/kb/908573