[英]OutOfMemoryException while reading a file
In my application I am reading a file using a windows service. 在我的应用程序中,我正在使用Windows服务读取文件。 This service reads the file every second.
该服务每秒读取一次文件。 This is the code I am using to read the file:
这是我用来读取文件的代码:
public static byte[] GetBytesFromFile(string fullFilePath)
{
FileStream fs = File.OpenRead(fullFilePath);
try
{
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
return bytes;
}
finally
{
fs.Close();
}
}
After some hours I am getting a System.OutOfMemoryException
. 几个小时后,我得到了
System.OutOfMemoryException
。 Am I doing anything wrong here? 我在这里做错什么吗?
Update: I am using the returned bytes in this code: 更新:我在此代码中使用返回的字节:
object s = null;
System.Reflection.Assembly a = Assembly.Load(bytes);
object o = a.CreateInstance("ID_" + report.ID.ToString().Replace("-", "_"));
Type t = o.GetType();
MethodInfo mi = t.GetMethod(name);
object[] values = new object[1];
values[0] = nameValue;
s = mi.Invoke(o, values);
return s;
With the edit, the problem is obvious: 通过编辑,问题很明显:
System.Reflection.Assembly a = Assembly.Load(bytes);
Here's the thing: assemblies do not unload from an AppDomain
. 事情是这样的:程序集不会从
AppDomain
卸载 。 There are some garbage-collectible things like DynamicMethod
- but not a full assembly. 有一些垃圾可收集的东西,例如
DynamicMethod
但不是完整的程序集。 If you are loading assemblies, the only safe way to do that is into a separate AppDomain
in the process. 如果要加载程序集,则唯一安全的方法是在过程中将其放入单独的
AppDomain
中。 Then you can jettison the AppDomain
when you are done with it (which unloads everything that is in it). 然后,您可以在使用完
AppDomain
抛弃它(卸载其中的所有内容)。
Actually, there is no guarantee that your existing code even works - Read
does not guarantee to read all the data. 实际上,不能保证您现有的代码也能正常工作 -
Read
并不能保证读取所有数据。 I have a pending blog post about that... 我有关于此的待定博客文章...
But: if the files are big, it is likely you are slowly saturating the LOH, which is a non-compacting heap. 但是:如果文件很大,则可能是慢慢使LOH饱和,这是一个非紧凑的堆。 The best advice I can offer is: don't read huge files into arrays.
我能提供的最佳建议是:不要将大文件读入数组。 Try to re-write the downstream code to work with either a
Stream
API, some kind of "reader" API, or some kind of parsing iterator block. 尝试重新编写下游代码以与
Stream
API,某种“读取器” API或某种解析迭代器块一起使用。
Without seeing how the rest of the code processes things, it is hard to say more. 如果不了解其余代码如何处理事情,就很难多说了。 However, it would be a good idea to run a memory profiler on the code to confirm that it is indeed the
byte[]
that are causing the memory issues. 但是,最好在代码上运行内存分析器,以确认确实是导致内存问题的
byte[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.