OutOfMemory例外对象数组大小数组、对象、大小、OutOfMemory

2023-09-04 00:36:51 作者:是时候炸学校了

我想拍摄为preadsheet数据到一个二维数组。我使用VSTO。

I am trying to capture a spreadsheet data in to a 2D array. I am using VSTO.

int rc = 1048576;
int cc = 1638;

string[,] arr = new string[rc, cc];

最后一行抛出内存溢出异常。我想显示消息,告知只有X元素可以捕获用户。

The last line throws Out of Memory exception. I would like to show message telling the user only 'X' elements can be captured.

经过MSDN和有16,777,216提到的行数的限制。没有列数限制为数据表。找不到限制无论是二维数组。

Checked MSDN and there is a row count limit mentioned of 16,777,216. No Column count limitation for datatable. Cant find limit either for 2D array.

我的问题是不是与为什么例外。我所寻找的是如果你正在做VSTO的开发,并有拍摄的工作表中的数据表来执行内存联接等,你需要这样做:

My issue is not with WHY the exception. What I am looking for is if you are doing VSTO development, and had to capture a worksheet in a DataTable to perform In-Memory joins etc, you will need to do this:

string[,] arr = new string[rc, cc]; 
Microsoft.Office.Interop.Excel.Range selection 
arr = selection.Value as string[,]; 

,然后从该数组数据表中的数据复制。现在,会是怎样的元素的用户应该选择一些理想的极限。因此,当选择超过这个标准,我可以设置行数/列数lmits和显示信息。

and then copy the data from that array to datatable. Now what will be the ideal limit for number of elements a user should select. So I can set that rowcount/columncount lmits and display message when selection exceeds this criteria.

推荐答案

让我们做数学题。您试图分配一个二维字符串数组1048576 * 1638 = 1717567488元素。的在x64串参考的大小是8个字节=>共1717567488 * 8 = 13740539904字节。这是一个关于 13 GB 的连续存储空间。为CLR单个分配最大的大小为2GB,所以你得到OutOfMemoryException异常这样的单块不能进行分配。

Let's do the math. You are trying to allocate a 2D string array with 1048576 * 1638 = 1717567488 elements. The size of string reference on x64 is 8 bytes => a total of 1717567488 * 8 = 13740539904 bytes. Which is about 13 GB of continuous memory space. Maximum size for single allocation for CLR is 2GB, so you are getting OutOfMemoryException as such single block can't be allocated.

请注意,这些字符串的量,即使都是1-2个字符,将30GB的字符串值,除了参考。还有什么比 OutOfMemoryException异常你希望得到?

Note that such amount of strings even when all are 1-2 characters long will take 30GB for string values in addition to references. What else than an OutOfMemoryException did you expect to get?