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

8
  • 2
    Does this answer your question? Out Of Memory exception on System.Drawing.Image.FromFile() Commented Mar 6, 2023 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. Commented Mar 6, 2023 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 Commented Mar 6, 2023 at 10:48
  • i have added code screen shots where it throw error. Commented Mar 6, 2023 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? for why. For instructions on formatting see How do I format my code blocks?. A minimal reproducible example showing what you have tried that did not work would maximize your chances of getting help. See How to Ask. Commented Mar 6, 2023 at 17:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.