1

I'm trying to use the PdfToImageConverter.GenerateImage method concurrently, in various threads:

new PdfToImageConverter
{
    ScaleTo = this.settings.ScaleTo
}
.GenerateImage(
    pdfContentStream,
    task.Page,
    ImageFormat.Png,
    outputContentStream);

Usually, the method works fine, but sometimes it throws an exception:

System.Exception: Invalid license key
at NReco.PdfRenderer.License.a.B()
at NReco.PdfRenderer.PdfToImageConverter.b(A )
at NReco.PdfRenderer.PdfToImageConverter.A(A )

I set the license info once at the start of our service:

NReco.PdfRenderer.License.SetLicenseKey(
    "PDF_Renderer_Bin_Pack_....",            
    "Pc...30=");

Is the PdfToImageConverter.GenerateImage thread-safe, and how can I use the method in a multithreaded environment?

Thanks!

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • Have you tried calling `SetLicenseKey()` in each thread? I don't imagine that's a particularly expensive call, given the heavy lifting this library does. – Robert Harvey May 02 '22 at 13:44

2 Answers2

0

This may happen when your license key initialization code (SetLicenseKey method call) is executed multiple times from several threads (in parallel). PdfToImageConverter can be used in multithread environment (each thread should use its own instance of the class).

SetLicenseKey should be executed only once (on the application start, from the 'main' thread); if this is not possible for some reason -- say, your service is Azure Function or AWS Lambda, you may use the following code snippet to guarantee a thread safety:

static object syncObj = new object();  // your class field

// code that initializes the license key
if ( NReco.PdfRenderer.License.GetLicenseKey()==null)
  lock (syncObj) {
    NReco.PdfRenderer.License.SetLicenseKey("owner_id", "key_value");
  }
Vitaliy Fedorchenko
  • 8,447
  • 3
  • 37
  • 34
  • Thank you for the response. I set the license key in Autofac module: ` using Autofac; public class NRecoModule : Module { protected override void Load(ContainerBuilder builder) { ... NReco.PdfRenderer.License.SetLicenseKey( owner, key); } } ` It is the only place where I call the `NReco.PdfRenderer.License.SetLicenseKey`. I'll inspect the code for a concurrency, but I think the code is run only once - at the start of my service. – Sergey Voronkov May 03 '22 at 14:20
  • @SergeyVoronkov try to use a code snippet with `lock`, it should help in any way – Vitaliy Fedorchenko May 05 '22 at 08:46
0

The problem has been resolved in the latest version. We used outdated product version.