开发者

C#: Use up almost all memory

My goal is to reach a开发者_如何学编程 point where I have filled up all available memory (note that I want to do this incrementally, so before my last allocation I have a minimal memory remaining). How can I do this?


for (object[] o = null;; o = new[] { o });


One option would be to create a list of some kind, and just keep adding junk to it in an infinite loop.

Depending on the precision needed, though, that could take a while - one option for speeding it up would be adding large structs to the list elements initially, then catching the OutOfMemoryError and trying again with smaller stuff until you've got the precision you need.


var junk = new LinkedList<byte[]>();
int allocSize = 100 * 1024 * 1024; // 100 MiB
while (allocSize > 0)
{
    try
    {
        junk.AddLast(null);
        junk.Last.Value = new byte[allocSize];
    }
    catch (OutOfMemoryException)
    {
        allocSize = (allocSize - 1) / 2;
    }
}


The scenario you are talking about sounds like it might be for testing an application.

You may want to look into load/stress testing tools. LoadRunner is the first one that comes to mind. It's not "in C#", and I am pretty sure it isn't free, but it may be the right tool for the job. Also, you may want to look into fault injection, if you all you want to see is how your program handles an OutOfMemory exception.

For exactly what you asked about, here's an article with an application that consumes RAM: http://msdn.microsoft.com/en-us/magazine/cc163613.aspx


Maybe something like this?

var bytes = new List<byte[]>();
var time = new TimeSpan(100);
while (true)
{
    bytes.Add(new byte[1024]);
    Thread.Sleep(time);
}


Keep adding a large buffer to a memory stream inside a while loop .


The LINQ way:

Enumerable.Range(0, int.MaxValue).ToArray();


        int size = 1024;
        var bytes = new List<byte[]>();
        while (true)
        {
            try
            {
                bytes.Add(new byte[size]);
            }
            catch
            {                   
                if (size == 1)
                {
                    throw;
                }
                size = size / 2;
            }
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜