System.OutOfMemoryException: 'Exception_WasThrown'

7.6k Views Asked by At

Follow my code:

[HttpGet]
public ActionResult StreamVideo(int type1, int type2)
{
    using (var ctx = new Entities())
    {
        var result = ctx.Table.Where(x => x.Type1 == type1 && x.Type2 == type2).FirstOrDefault();

        byte[] video_byte = result.Video;

        return new RangeFileContentResult(video_byte, "video/x-msvideo", "NameFile.mp4", DateTime.Now);
    }
}

I have a "modal bootstrap" where it has video content.When closing modal and opening again, it gives problem:

System.OutOfMemoryException: 'Exception_WasThrown'

enter image description here

Problem occurs on line:

var result = ctx.Table.Where(x => x.Type1 == type1 && x.Type2 == type2).FirstOrDefault();

Any solution ?

1

There are 1 best solutions below

6
On

When retrieving large amounts of varbinary data you need to be careful that you don't overtax the Large Object Heap. Consider retrieving the data as a stream instead. EntityCommand and SqlCommand can both retrieve readers, and you can get a stream from them.

SqlClient Streaming

using (connection)
{
    SqlCommand command = new SqlCommand(
      $"SELECT Video FROM Table where Type1={type1} and Type2={type2};",
      connection);
    connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    reader.Read();
    var stream = reader.GetStream(0);

   ... Use the stream here...
}