PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Thread safety, IndexOutOfRangeException
https://forum.pdfsharp.net/viewtopic.php?f=3&t=3836
Page 1 of 1

Author:  tutch [ Wed Aug 29, 2018 1:45 pm ]
Post subject:  Thread safety, IndexOutOfRangeException

Version 1.50.4845-RC2a

When running in multiple threads I get this repeatedly.

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at PdfSharp.Fonts.OpenType.OpenTypeFontface.CreateFontSubSet(Dictionary`2 glyphs, Boolean cidFont)
at PdfSharp.Pdf.Advanced.PdfCIDFont.PrepareForSave()
at PdfSharp.Pdf.Advanced.PdfType0Font.PrepareForSave()
at PdfSharp.Pdf.Advanced.PdfFontTable.PrepareForSave()
at PdfSharp.Pdf.PdfDocument.PrepareForSave()
at PdfSharp.Pdf.PdfDocument.DoSave(PdfWriter writer)
at PdfSharp.Pdf.PdfDocument.Save(Stream stream, Boolean closeStream)

Author:  sambutle [ Tue Sep 06, 2022 5:29 am ]
Post subject:  Re: Thread safety, IndexOutOfRangeException

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains. Indexing an empty list will always throw an exception. Use a method like Add to append the item to the end of the list, or Insert to place the item in the middle of the list somewhere, etc. You cannot index into a c# list if that offset doesn't exist. IndexOutOfRangeException exception is thrown as a result of developer error. Instead of handling the exception, you should diagnose the cause of the error and correct your code.

Handling the Exception:

Use for-each loop: This automatically handles indices while accessing the elements of an array.

Use Try-Catch: Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, C# won’t let you access an invalid index and will definitely throw an IndexOutOfRangeException. However, we should be careful inside the block of the catch statement, because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.

Author:  TH-Soft [ Tue Sep 06, 2022 11:51 am ]
Post subject:  Re: Thread safety, IndexOutOfRangeException

sambutle wrote:
Instead of handling the exception, you should diagnose the cause of the error and correct your code.
IIRC this should no longer be an issue with later versions of PDFsharp (1.50.5147 or 1.51.5185-beta).

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/