我需要从 ResourceIntensiveTask 中发布一个 5MB 的文件,其中操作系统将最大内存使用量设置为 5MB。因此尝试直接从存储中流式传输文件,但与 HttpWebRequest 关联的 Stream 的大小不断增长。这是代码:
public void writeStream(Stream writer, string filesource, string filename)
{
var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
var f = store.OpenFile(filesource, FileMode.Open, FileAccess.Read);
store.Dispose();
byte[] buffer = Encoding.UTF8.GetBytes(String.Format(@"Content-Disposition: form-data; name=""file""; filename=""{0}""\n", filename));
writer.Write(buffer, 0, buffer.Length);
buffer = Encoding.UTF8.GetBytes("Content-Type: application/octet-stream\n");
writer.Write(buffer, 0, buffer.Length);
long initialMemory = Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage;
buffer = new byte[2048];
int DataRead = 0;
do
{
DataRead = f.Read(buffer, 0, 2048);
if (DataRead > 0)
{
writer.Write(buffer, 0, DataRead);
Array.Clear(buffer, 0, 2048);
}
} while (DataRead > 0);
double increasedMemory = ((double)Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage - initialMemory) / 1000000;
buffer = Encoding.UTF8.GetBytes("\n--" + boundary + "\n--");
writer.Write(buffer, 0, buffer.Length);
writer.Flush();
}
increaseMemory调试变量用于获取文件被读取并流式传输到 HttpWebRequest 之前和之后的差异内存,它几乎给出了文件的确切大小(5MB),这意味着进程内存正在增加 5MB。
我还将AllowReadStreamBuffering =false 设置为 HttpWebRequest。
如何保持低内存?内存使用限制为 5MB 时如何上传大文件?