How to Fix the System.OutOfMemoryException Error

“Exception of type ‘System.OutOfMemoryException’ was thrown” means a .NET program could not allocate the memory an operation needed, or encountered an object’s capacity limit. It does not necessarily mean the computer has run out of physical RAM. The fix depends on the failing process, its architecture, and whether the workload causes a large allocation or steadily growing memory use.

Use the symptoms below to choose what to investigate first.

Symptom Likely Cause Targeted Fix
A large import, export, report, or file fails An oversized allocation or several in-memory copies Stream the data or process bounded batches
Memory grows across repeated requests or jobs Retained objects, an unbounded cache, or unmanaged resource leaks Compare memory snapshots, remove unwanted references, and dispose resources
The process reaches a ceiling while the host still has memory Process address-space restrictions Use a compatible build and host with a larger address space
Failures occur only under heavy concurrent load Too many memory-intensive operations running together Bound concurrency and check available memory
StringBuilder.Insert fails at a predictable length The operation exceeds the builder’s configured capacity Validate the resulting length or write output in chunks
The application fails only in a container or hosted environment A hosting memory limit or different deployment architecture Check the effective limit and actual deployed process

What the .NET Out-of-Memory Error Means

Memory allocation involves more than free RAM. A .NET process needs available address space, memory backing from the operating system, and enough room within any applicable hosting limits. A large object also needs a sufficiently large contiguous region of virtual address space, not necessarily contiguous physical RAM.

That is why an allocation can fail even when a system monitor shows available memory. The process may be constrained by its architecture, its address space may be fragmented, or the requested object may simply be too large.

An allocation failure can happen in almost any method or property assignment that needs memory. A capacity check can also produce this exception, according to Microsoft’s .NET documentation.

The line that throws the exception identifies the failed allocation, not necessarily the code that consumed the memory.

For example, an application might retain large query results for hours and then fail while formatting a small log message. Fixing the logging statement would not remove the retained data.

How to Fix the .NET Out-of-Memory Error

Identify the failing process, test smaller workloads, and check process architecture and address-space limits to isolate the memory constraint.

Step 1: Identify the Failing Process and Operation

  1. Save the complete exception and stack trace. Match the exception type to System.OutOfMemoryException, rather than relying on a generic “not enough memory” dialog. In HRESULT-based logs, its identifier is COR_E_OUTOFMEMORY, with the value 0x8007000E.
  2. Identify the process that failed. It might be your application, a web worker, a compiler, a build task, an Excel add-in host, or a background service. Memory usage in a different process will not explain its allocation limits.
  3. Record the trigger and environment. Capture the input size, operation, concurrent workload, application version, .NET version, operating system, and whether the failure occurs immediately or after sustained use.
  4. Preserve evidence before restarting when practical. Save existing logs and memory metrics. If service restoration is urgent, restart through the application’s normal recovery mechanism, but keep the incident details.

Reproduce the failure in a controlled environment when possible. Before retrying a partially completed import or job, check whether it already wrote data; an automatic retry can duplicate work.

Step 2: Test With a Smaller Workload

Start with reversible changes that reveal whether the problem depends on workload size.

  1. Reduce the failing operation’s scope: fewer report rows, a smaller date range, a smaller file, or fewer items per batch.
  2. Run memory-intensive work sequentially instead of launching many operations together.
  3. Monitor the failing process while repeating the operation, and verify that the resulting output is complete.

If a smaller workload succeeds, you have a useful workaround and evidence of workload-dependent memory demand. You have not yet established whether the underlying cause is a large allocation, accumulated data, or overlapping jobs.

If memory remains elevated and keeps increasing across repeated runs, investigate retained objects rather than only reducing each request. If memory spikes during one operation and later stabilizes, focus on peak allocation size.

Closing unrelated applications can help when the machine is genuinely under memory pressure. It cannot remove a process address-space limit, repair a leak, or change an object’s configured capacity.

Step 3: Check Process Architecture and Memory Limits

  1. Measure the actual process architecture. A 64-bit operating system does not guarantee that your application runs as a 64-bit process. For an application you control, temporarily record these values in its own startup code, before it is under memory pressure:
    System.Console.WriteLine(
        $"Process is 64-bit: {System.Environment.Is64BitProcess}");
    System.Console.WriteLine(
        $"Operating system is 64-bit: {System.Environment.Is64BitOperatingSystem}");

    Use your normal logger instead of console output if necessary. Run the diagnostic build in the environment where the failure occurs.

  2. Check whether address space is the constraint. For Windows-hosted .NET applications, common 32-bit process ceilings range from 2 GB of virtual user-mode memory on a 32-bit system to a maximum of 4 GB on a 64-bit system, per Microsoft’s .NET reference. Confirm the process bitness and operating system bitness; the Windows executable’s large-address-aware setting also affects the actual ceiling. A 64-bit process has much more address space, up to 8 TB in Microsoft’s .NET reference comparison, although operating-system versions have different limits, so that comparison is not a universal modern ceiling. These figures describe virtual address space, not installed RAM or guaranteed allocatable memory.
  3. Change the target only when architecture is the problem. Recompile for a 64-bit platform compatible with the deployment machine. On an x64 host, set the application’s platform target to x64 and disable Prefer 32-bit where that option exists. Ensure the runtime and native dependencies support the new architecture. Any CPU does not prove that the deployed process is running with the intended architecture. Libraries also inherit the architecture of their host process; rebuilding a library alone cannot change that host.
  4. Check system memory backing and deployment constraints. Inspect available memory and, on Windows, system commit usage and the commit limit. If commit is exhausted, review workload demand and the paging-file configuration rather than assuming free disk space automatically provides usable memory.

After changing the build or host configuration, deploy it, restart the affected process normally, verify its actual architecture, and rerun the failing operation. If memory continues growing without stabilizing, the larger address space has postponed the failure rather than fixed its cause.

Step 4: Reduce the Failing Allocation

Use the stack trace to locate the operation requesting memory, then inspect the data it creates and copies.

  1. Find whole-data-set materialization. Look for whole-file reads, large arrays, repeated string concatenation, in-memory report generation, or calls such as ToList() and ToArray() on large results. Check whether parsing, conversion, serialization, and compression create additional copies.
  2. Check explicit object capacity. Before an Insert or another operation increases StringBuilder.Length, compare the intended result with StringBuilder.MaxCapacity. An insertion that would exceed the configured capacity can throw this exception without machine-wide memory exhaustion. Validate the requested length using arithmetic that cannot overflow; reject invalid input or write the output incrementally.
  3. Replace full buffering with bounded processing. Read, transform, and write a portion of the data at a time. If later processing requires retaining the data, serialize intermediate results to a file instead of keeping the entire data set in memory.

For example, this C# method reads and writes a text file one line at a time:

using System.IO;
public static class TextExporter
{
    public static void WriteLines(string inputPath, string outputPath)
    {
        using var output = new StreamWriter(outputPath);
        foreach (string line in File.ReadLines(inputPath))
        {
            output.WriteLine(line);
        }
    }
}

Use different input and output files. This is a line-oriented text example, not a byte-for-byte file copy: writing the lines can change encoding and line endings.

Its memory use still depends on the longest individual line. For enormous lines or binary data, use bounded character or byte buffers instead. Streaming also fails to reduce memory if an upstream API has already loaded the complete input.

For database workloads, retrieve only needed columns and use bounded batches with stable ordering. Do not append every processed batch to a growing collection, which recreates the original problem.

After the change, test representative input, verify the output’s contents and completeness, and then rerun the original workload while observing peak memory.

Step 5: Investigate Memory That Keeps Growing

If repeated operations steadily increase memory use, inspect what remains alive.

  1. Collect comparable measurements before the failure. Record process memory and managed-heap usage before and after repeated runs of the same workload. Capture heap snapshots in a controlled reproduction with enough memory headroom; collecting diagnostics during an active memory crisis can fail.
  2. Compare retained objects, not just allocation counts. In a .NET memory profiler, look for objects whose retained size increases and inspect the references keeping them alive. Common causes include static collections, unbounded caches, event subscriptions, queued work, and accumulated task results.
  3. Investigate native allocations separately. If process memory grows while the managed heap remains relatively stable, inspect native libraries and unmanaged resources. This is a diagnostic clue, not proof of a particular leak.
  4. Correct ownership and lifetime. Bound caches and queues, remove unintended references, and dispose IDisposable resources when their owner finishes using them. Use using statements for suitable local resources, but do not dispose shared objects while other operations still need them.

Garbage collection cannot reclaim objects that remain reachable. Calling GC.Collect() is therefore not a general fix for retained data, oversized allocations, or address-space restrictions.

Rebuild and rerun the repeated workload after the change. Check that retained memory stops increasing unexpectedly and that disposing resources has not broken later operations. Protect diagnostic dumps because they can contain application data and credentials.

Special Cases for Websites, Builds, and Containers

Websites, builds, and containers require checking their actual processes, workloads, architectures, and effective memory limits.

ASP.NET Websites and IIS

A stack trace ending in a framework handler does not establish that the framework component caused the memory buildup. Resource generation, page rendering, or logging may simply be the next operation that needs an allocation.

Identify the worker process serving the affected site and compare its memory with request volume. Check for large in-memory responses, cached report results, and overlapping requests.

If architecture is the constraint, verify that the IIS application pool can run the application and its dependencies in the intended architecture. Change the pool configuration only after checking compatibility, recycle it through the normal deployment procedure, and retest representative requests.

Recycling can restore availability, but scheduled recycling alone does not establish that a leak is fixed.

MSBuild and CI Builds

Read the build log from the first substantive failure, not just the final exception.

For example, if a compiler first produces C1060: compiler is out of heap space and a later build task fails while parsing compiler output, investigate overall build memory pressure. The final parsing failure may be secondary.

Reduce parallel build work and other memory-heavy jobs sharing the runner. Verify the architecture of the actual build tools and child processes, rather than inferring it from the operating system.

Rerun the same build with those changes and confirm both successful completion and the absence of the earlier compiler memory error. If the workload still exceeds available capacity, use a runner with sufficient memory or reduce the build’s peak demand.

Docker and Kubernetes Workloads

A container can have less usable memory than its host. Check the effective container memory limit and the runtime’s view of available memory, not just the host’s RAM.

Also distinguish a managed exception from an operating-system kill. Kubernetes may report OOMKilled when a process is terminated for memory pressure; the application may have no opportunity to throw or log a .NET exception.

If the application’s legitimate working set exceeds its limit, adjust the deployment’s memory allocation only after checking node capacity. If memory grows continuously or one request creates excessive allocations, fix that behavior instead of repeatedly increasing the limit.

Redeploy the workload, repeat the triggering operation, and confirm that memory remains within the effective limit without container restarts.

How to Confirm the Fix and Prevent Recurrence

A successful restart is not enough. Validate the change against both the original failure and repeated use.

  • Run the original input and operation, not only a reduced test.
  • Verify output correctness, including whether an interrupted job left partial or duplicate results.
  • Test expected concurrency and overlapping background work.
  • Observe peak process memory and retained managed memory after warm-up.
  • Confirm the production process uses the intended architecture and hosting limits.
  • Check logs for new exceptions, worker restarts, or container terminations.

Prevent recurrence by bounding input sizes, caches, queues, and concurrent jobs. Keep memory metrics alongside workload metrics so that a growing backlog or unusually large request is visible before allocation fails.

If the application still fails, collect a pre-failure memory snapshot and a reproducible input for deeper analysis. The next useful evidence is what the process retained and what allocation it attempted, not a screenshot of the exception message.

Frequently Asked Questions

Can OutOfMemoryExceptions Be Caught and Handled?

Yes, an OutOfMemoryException can be caught, but catching it does not make continued execution reliable. For a catastrophic allocation failure, Environment.FailFast is Microsoft’s documented termination option when the exception is caught, rather than attempting normal recovery in an exhausted process; it bypasses finally blocks and finalizers, so it is not a cleanup mechanism. Keep failure handling minimal, because logging and cleanup can themselves allocate memory. Predictable capacity errors are better prevented through validation than handled as general memory exhaustion, consistent with Microsoft’s exception guidance.

Can a CPU Limit Cause an Out-of-Memory Exception?

A CPU limit does not directly reduce the memory available for allocations. It can indirectly contribute if slower processing allows requests, messages, or task results to accumulate in memory. Measure queue growth and memory together, then bound the backlog and concurrency rather than assuming a CPU increase alone will fix the problem.

What Should I Check for This Error in AFO or Tagetik?

Identify which process actually throws the exception before changing product settings. If AFO means SAP Analysis for Office, capture the Excel/add-in versions, host process architecture, and the workbook or refresh operation involved; for Tagetik, establish whether the failure originates in the desktop integration or a server-side operation. Test a reduced report or refresh scope and preserve the full error details so the application administrator can distinguish workload size, hosting limits, and a software defect.

Is This the Same as an Out-of-Memory Error in Java?

No. Java normally reports java.lang.OutOfMemoryError, not a .NET exception. Diagnose the Java error’s specific message and the failing JVM’s heap, native memory, or container limit; .NET platform-target changes do not configure Java memory. If a Java-based workflow displays a System exception, investigate whether a .NET service or integration component produced it.

When can System.OutOfMemoryException occur?

System.OutOfMemoryException can occur when the common language runtime cannot allocate enough contiguous virtual memory for an operation or when code tries to extend a StringBuilder beyond its MaxCapacity. The exception can be thrown by any method call or property assignment that requires a memory allocation.