Using Semaphores (Thread Locking) in Plugins RRS feed

  • Question

  • I am reviewing the code (below) and came across a Plugin that is used to generate unique auto

    numbers for invoices and contacts. The plugin ensures unique numbers are created by using a

    Semaphore to ensure only one instance of the plugin creates an auto number at any given time.

    The code achieves its purpose of creating unique auto generated numbers however the code concerns

    me as it is implementing thread locking. 

    Are there are any best practices for Plugin development regarding thread locking? 
    Has anyone seen or used similar code before?
    Is there any chance of the Plugin timing out because of the thread locking?

    protected void ExecutePreInvoiceCreate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IServiceProvider serviceProvider = localContext.ServiceProvider; IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; ITracingService tracingService = localContext.TracingService; Semaphore semaphore = new Semaphore(1, 1, "PreInvoiceCreate"); if (context.InputParameters.Contains("Target")

    && context.InputParameters["Target"] is Entity) { targetEntity = (Entity)context.InputParameters["Target"]; // test semaphore try { semaphore.WaitOne(300000); } catch (Exception) {} // Psuedo Code to demonstrate what is going on var id = GetIdFromConfigurationEntity(); id = IncrementId(id); SetNextIdInConfigurationEntity(); targetEntity.Attributes["autoGeneratedNumber"] = id; semaphore.Release(); } }

    • Edited by Dean776 Wednesday, May 18, 2016 4:01 AM Improved Formatting
    Wednesday, May 18, 2016 4:00 AM

All replies

  • Auto-numbering has been a pet peeve of mine for years. What I recommend in this case is to leverage the database transaction locking behavior to enforce serialized access to the numbering sequence(s) instead of trying to use semaphores, shared files, or other locking mechanisms. Using thread locking of any kind will ONLY work on a single machine - not across servers in a web farm/load balancer situation, which most of our customers have. https://www.greenbeacon.com/insights/how-to-implement-robust-auto-numbering-using-transactions-in-microsoft-dynamics-crm/
    Thursday, May 19, 2016 2:20 PM
  • I agree with the previous post that the only reliable option uses database locking. A couple of other comments on thread locking in plug-ins:

    1. Even on one server, thread locking isn't reliable. For example, if running in the sandbox, CRM may spawn multiple sandbox worker processes
    2. Plugins could time out if you use thread locking. A plugin will timeout after 120 seconds

    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Thursday, May 19, 2016 4:08 PM