0

We have our c# web application which use in-memory to store data using multi threading, our application work till 14-15 days after that it start to throw OutOfMemoryException for thread and for reading cache due to which our application get crash we need to give hard reset to start application properly. I want a way to catch which cache code is taking large memory or cache is get created repeat for same or any other problem is causing this, below is some code which start to throws:
Thread

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Threading.Thread.StartInternal(IPrincipal principal, StackCrawlMark& stackMark) at System.Threading.Thread.Start(StackCrawlMark& stackMark) at System.Threading.Thread.Start()

Code snippet from where it is throwing above exception:

public void PreloadSavedCartsFor(LoggedInUser loggedinUser)
    {
        System.Web.HttpContext ctx = System.Web.HttpContext.Current;
        System.Threading.Thread preloadcustomercarts = new System.Threading.Thread(
            delegate()
            {
                System.Web.HttpContext.Current = ctx;
                try
                {
                    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Session != null)
                    {
                        System.Web.HttpContext.Current.Session["SavedCarts"] = LoadCustomerSavedCarts(loggedinUser);
                    }
                }
                catch
                {
                    //TODO LOg Exception
                }
            });
        preloadcustomercarts.Start();
    }


Image Read

System.OutOfMemoryException: Out of memory. at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement) at ImageService.FileImageProvider.RetrieveImage(String name, Boolean checkCacheExpiration) in c:\Builds\22\ImageService\FileImageProvider.cs:line 215 at CreateResizedImageFromOriginalImage(String ImageName, String ImageDimension, String newsizename, String& returnName, String& contentType) in Store\Inetpub\wwwroot\ViewHelper\Product.cs:line 680

Below is code snippet we use to read and save image :
ImageService dll code:

public override Image RetrieveImage(string name, bool checkCacheExpiration = true)
    {
        lock (_Sync)
        {
            if (checkCacheExpiration ? Exists(name) : this.FileExists(name))
                return Image.FromFile(ResolvePath(name));
            else
                return null;
        }
    }

code from where above method is getting called :

private static void CreateResizedImageFromOriginalImage(string ImageName, string ImageDimension, string newsizename, ref string returnName, ref string contentType)
    {
        using (System.Drawing.Image originalImage = ImageService.RetrieveImage(ImageName, false))
        {
            if (originalImage != null)
            {
                contentType = ImageService.RetriveImageContentType(ImageName);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                originalImage.Save(ms, originalImage.RawFormat);
                Byte[] data = ms.ToArray();

                // Create the stream of image & generate new image with specified width & height
                int imageheight = 0;
                int imagewidth = 0;
                if (!string.IsNullOrEmpty(ImageDimension.Split('X')[0]))
                    imagewidth = Convert.ToInt32(ImageDimension.Split('X')[0], System.Globalization.CultureInfo.InvariantCulture);
                if (!string.IsNullOrEmpty(ImageDimension.Split('X')[1]))
                    imageheight = Convert.ToInt32(ImageDimension.Split('X')[1], System.Globalization.CultureInfo.InvariantCulture);

                byte[] newdata = ImageGenerator.CreateImageThumbnail(data, contentType, imageheight, imagewidth, false);

                if (newdata.Length > 0)
                {
                    ImageService.SaveImage(newsizename, newdata, contentType);
                    returnName = ImageService.RetrieveImageUrl(newsizename);
                }
            }
        }
    }

We have written FromFile method in using, so object of FromFile will get dispose after use.

Can anyone tell me if this error occur how to handle it so it should not break our application and way to find reason behind start throwing this error.

Thanks,
Sandy

Sandy
  • 57
  • 1
  • 17
  • 2
    Does this answer your question? [Out Of Memory exception on System.Drawing.Image.FromFile()](https://stackoverflow.com/questions/1108607/out-of-memory-exception-on-system-drawing-image-fromfile) – Matt Evans Mar 06 '23 at 10:38
  • 2
    Post your code. In 99% of cases, an OOM exception isn't caused because RAM was exhausted. The `System.Drawing` namespace is a wrapper over Windows' GDI+ which has a limited number of graphic object handles. If you forget to dispose your objects and bitmaps you'll quickly exhaust them, resulting in an OOM. GDI+ was created to draw on desktop screens, not general purpose image processing. – Panagiotis Kanavos Mar 06 '23 at 10:44
  • 2
    In general `System.Drawing` isn't the best choice as it depends on GDI+ and Windows, isn't thread-safe and doesn't support the latest formats and algorithms. That's simply not its job. There are far better, cross-platform options like ImageSharp, SkiaSharp. System.Drawing was deprecated in .NET Core and [generates compiler warnings in .NET 6](https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only) – Panagiotis Kanavos Mar 06 '23 at 10:48
  • i have added code screen shots where it throw error. – Sandy Mar 06 '23 at 11:08
  • Please [edit] your question to include your code and errors as **text** rather than as screenshot(s). On stack overflow images should not be used for textual content, see [*Why should I not upload images of code/data/errors?*](https://meta.stackoverflow.com/a/285557) for why. For instructions on formatting see *[How do I format my code blocks?](https://meta.stackexchange.com/q/22186)*. A [mcve] showing what you have tried that did not work would maximize your chances of getting help. See [ask]. – dbc Mar 06 '23 at 17:38
  • Hi @dbc, i have updated question, is changes okay now? – Sandy Mar 07 '23 at 06:54
  • To emphasise Panagiotis's comment - [https://learn.microsoft.com/en-us/dotnet/api/system.drawing?view=net-7.0#remarks](https://learn.microsoft.com/en-us/dotnet/api/system.drawing?view=net-7.0#remarks): "not supported in Windows services and ASP.NET Core and ASP.NET apps". So stop chasing trying to make this work with an unsupported library and find an alternative. – Damien_The_Unbeliever Mar 07 '23 at 07:02
  • it does work but after 13-14 days it started to give out of memory exception – Sandy Mar 07 '23 at 07:30

0 Answers0