Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

Visual Studio 2022 スナップショットでマネージドヒープを確認する

0
Posted at

はじめに

Visual Studio 2022 スナップショットでマネージドヒープを確認する備忘録です。

改訂履歴

  • 2026/08/23 : 初版公開。

本文

1. 環境

  • .NET 8.0
  • Visual Studio Community 2022

2. 事前準備

検証用の簡易なプログラムを用意します。

※ソースは長くなるので、折り畳みます。
MemoryResource.cs
namespace MemoryUsageExample;

/// <summary>
/// メモリリソースを表します。
/// </summary>
internal sealed class MemoryResource : IDisposable
{
    private byte[]? _data = new byte[1024 * 1024];

    /// <inheritdoc/>
    public void Dispose() => _data = null;
}
Program.cs
namespace MemoryUsageExample;

/// <summary>
/// アプリケーションのエントリポイントを定義します。
/// </summary>
internal static class Program
{
    private static readonly List<MemoryResource> s_resources = new();

    /// <summary>
    /// アプリケーションのエントリポイントです。
    /// </summary>
    [STAThread]
    internal static void Main()
    {
        for (int i = 0; i < 100; i++)
        {
            s_resources.Add(new MemoryResource());
        }

        // Dispose 前のスナップショットを取得する。
        MessageBox.Show("Please take a memory snapshot before Dispose.");

        foreach (MemoryResource resource in s_resources)
        {
            resource.Dispose();
        }

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        // Dispose 後のスナップショットを取得して、メモリ使用量の変化を確認する。
        MessageBox.Show("Please take a memory snapshot after Dispose.");
    }
}

3. 手順

デバッグビルドし、調査したいタイミングで「スナップショットの作成」をクリックします。今回はメッセージボックスで処理を一時停止していますが、ブレークポイントで止めても問題ありません。

スナップショットが作成されました。「ヒープを表示」をクリックします。

検索ボックスに MemoryResource を入力すると、さくっと確認できます。

同様の手順で 2 回目のスナップショットを取得し、ヒープを表示します。

2 回目のスナップショットでは MemoryResource が保持していた byte[] が回収されたことが分かります。

4. 参考

おわりに

メモリの使用量が異常に多い時や、不要になったはずのオブジェクトが残り続けている時などに、スナップショットを取って確認しています。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?