How does catching an OutOfMemoryException work?

后端 未结 5 1065
再見小時候
再見小時候 2021-01-01 11:29

I am a little bit confused about the fact that we can just catch an OutOfMemoryException using a try/catch block.

Given the following code:



        
5条回答
  •  北海茫月
    2021-01-01 11:48

    The OutOfMemoryException is quite possibly thrown because you are running a 32 bit program, with the memory graph you have not indicated how much ram the system has, so perhaps try building it as a 64 bit, and maybe use MemoryFailPoint to prevent this occurring anyway.

    You could also let us know what is in the OutOfMemory() function for a clearer picture.

    P.S. StackOverFlow is the only error which cannot be handled.

    Edit: as mentioned above, and I thought it only logical and hence didn't mention it earlier, if you for example try to allocate more memory than you have 'spare' then it is not possible to do so and an exception occurs. As you are allocating large arrays with your data.Add() it falls over before the final 'illegal' add occurs, hence there is still free memory.

    So I would assume that it is at this point data.Add(buffer); the issue occurs during the building of the array when you trip the 2GB process limit by adding a 400MB byte array to 'data', e.g. an array of around 1 billion objects at 4 bytes a piece I would expect to be around 400MB.

    P.S. Up until .net 4.5 max process memory allocation is 2GB, after 4.5 larger are available.

提交回复
热议问题