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();
}
}