1

IIS アプリケーション プール プロセスの 1 つで非常に奇妙な問題が発生しています。最近 System.OutOfMemoryException エラーが発生しており、何が起こっているのかを正確に把握しようとしています。基本的に、Web サービスを使用して DAM からファイルを取得するスクリプトがあります。次に、ファイルがバイト配列に格納されていることを確認し、応答を使用してファイルを出力します。唯一問題があったのは PDF が 20MB を超えている場合で、時々エラーが発生するようです。アプリ プールのメモリを増やすと、一時的に問題が解決します。w3wp.exe プロセスを観察したところ、このスクリプトを実行するとメモリが最大 400MB 増加し、最大のファイルが 45MB になり、この種の動作が発生することがわかりました。問題は毎晩解消しているようで、朝になるとしばらくは機能し、その後同じことをやり始めます. このアプリケーションは c# asp.net アプリケーションです。sharepoint 内で実行されます。

しばらくサービスを見た後、これらの PDF はブラウザー ウィンドウでレンダリングされるため、ファイルが完全にダウンロードされるまでメモリから解放されないことに気付きました。これは理にかなっていますが、これは私の問題であることがわかります。複数の人がファイルをロードしている場合、平均 (ファイルのダウンロードなし) のメモリ使用量は 385,000 KB です。アプリケーション プールの制限である 900,000 ~ 1,100,000 KB に簡単に達する可能性があります。

私は正確な答えを探しているわけではありませんが、アイデアがすべてなくなっているので、向かうべき方向のようなものです.

4

2 に答える 2

10

ファイルデータをバイトの配列としてメモリに取り込むと、Webサーバーに大きな負荷がかかります。

ファイルデータ全体をバイトの配列に格納する代わりに、ファイルストリームを応答ストリームにチャンクで書き込んでみてください。

疑似例:

context.Response.Buffer = false;

byte[] buffer   = new byte[4096];
int bytesRead   = 0;

using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    while ((bytesRead = stream.Read(buffer, 0 , buffer.Length)) > 0)
    {
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        context.Response.OutputStream.Flush();
    }
}

ここでの考え方は、ファイルストリームを読み取るたびに、ファイルデータのチャンクをメモリに取り込み、それを応答に書き込むことだけです。応答バッファリングが無効になっていることに注意してください。また、ファイルストリームを使用して別のストリームデータソースに置き換えることができます(SQLデータベースからバイナリデータを読み取るときにこのアプローチを使用しました)。

編集:(SQLからHTTP応答にデータをストリーミングする方法への応答)

SQL Serverデータベーステーブル(varbinary(max)列など)からデータをストリーミングするには、SqlCommandでシーケンシャルアクセスを使用します。

#region WriteResponse(HttpContext context, Guid id)
/// <summary>
/// Writes the content for a media resource with the specified <paramref name="id"/> 
/// to the response stream using the appropriate content type and length.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> to write content to.</param>
/// <param name="id">The unique identifier assigned to the media resource.</param>
private static void WriteResponse(HttpContext context, Guid id)
{
    using(var connection = ConnectionFactory.Create())
    {
        using (var command = new SqlCommand("[dbo].[GetResponse]", connection))
        {
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add("@Id", SqlDbType.UniqueIdentifier);
            command.Parameters.AddReturnValue();

            command.Parameters["@Id"].Value = id;

            command.Open();

            using(var reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
            {
                if(reader.Read())
                {
                    WriteResponse(context, reader);
                }
            }
        }
    }
}
#endregion

#region WriteResponse(HttpContext context, SqlDataReader reader)
/// <summary>
/// Writes the content for a media resource to the response stream using the supplied <paramref name="reader"/>.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> to write content to.</param>
/// <param name="reader">The <see cref="SqlDataReader"/> to extract information from.</param>
private static void WriteResponse(HttpContext context, SqlDataReader reader)
{
    if (context == null || reader == null)
    {
        return;
    }

    DateTime expiresOn      = DateTime.UtcNow;
    string contentType      = String.Empty;
    long contentLength      = 0;
    string fileName         = String.Empty;
    string fileExtension    = String.Empty;

    expiresOn               = reader.GetDateTime(0);
    fileName                = reader.GetString(1);
    fileExtension           = reader.GetString(2);
    contentType             = reader.GetString(3);
    contentLength           = reader.GetInt64(4);

    context.Response.AddHeader("Content-Disposition", String.Format(null, "attachment; filename={0}", fileName));

    WriteResponse(context, reader, contentType, contentLength);

    ApplyCachePolicy(context, expiresOn - DateTime.UtcNow);
}
#endregion

#region WriteResponse(HttpContext context, SqlDataReader reader, string contentType, long contentLength)
/// <summary>
/// Writes the content for a media resource to the response stream using the 
/// specified reader, content type and content length.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> to write content to.</param>
/// <param name="reader">The <see cref="SqlDataReader"/> to extract information from.</param>
/// <param name="contentType">The content type of the media.</param>
/// <param name="contentLength">The content length of the media.</param>
private static void WriteResponse(HttpContext context, SqlDataReader reader, string contentType, long contentLength)
{
    if (context == null || reader == null)
    {
        return;
    }

    int ordinal     = 5;
    int bufferSize  = 4096 * 1024; // 4MB
    byte[] buffer   = new byte[bufferSize];
    long value;
    long dataIndex;

    context.Response.Buffer         = false;
    context.Response.ContentType    = contentType;
    context.Response.AppendHeader("content-length", contentLength.ToString());

    using (var writer = new BinaryWriter(context.Response.OutputStream))
    {
        dataIndex   = 0;
        value       = reader.GetBytes(ordinal, dataIndex, buffer, 0, bufferSize);

        while(value == bufferSize)
        {
            writer.Write(buffer);
            writer.Flush();

            dataIndex   += bufferSize;
            value       = reader.GetBytes(ordinal, dataIndex, buffer, 0, bufferSize);
        }

        writer.Write(buffer, 0, (int)value);
        writer.Flush();
    }
}
#endregion
于 2011-07-29T15:04:46.343 に答える
1

Oppositional は、ファイル自体の処理について非常に優れたアドバイスを提供しています。また、Web 処理で使用している可能性のある参照も調べます。セッション状態またはアプリケーション状態に何かを保存しますか? その場合は、それらを注意深く追跡して、ファイルの処理に関連するページやその他のものを順番に指していないことを確認してください。

これについて言及したのは、数年前にオブジェクトをアプリケーション状態にしたことによる厄介な「リーク」があったためです。そのオブジェクトがページ イベントをサブスクライブしていることが判明しました。このオブジェクトは一度も停止していないため、すべてのページも停止していません。おっとっと

于 2011-07-29T15:08:40.640 に答える