title: Locking/Synchronize problem - Backend code execute faster than database saving
body: <p>I have a simple example about generating invoice number for new invoice below:</p>
  <pre><code>// API generate invoice number
  public void PublishInvoice(Object invoiceData)
  {
      lock (companyInfo) // (1) if request is the same company will be blocked
      {
          int invoiceNo = GetNextNo(); // (2) get new invoice number from database (next no = current no + 1)
          invoiceData.InvoiceNo = invoiceNo; // (3) set invoice number to invoice data
          Save(invoiceData); // (4) save invoice data to database
      }
  }
  </code></pre>
  <p>The problem that I encountered is if two requests simultaneously call this API, the second request will be blocked at (1), when the first request completed executing (after 4) then the second request executes (2) to get next invoice number but the invoice of the first request hasn't saved to the database yet, so the second invoice got the same invoice number with the first invoice.</p>
  <hr />
  <p>My question is how can I handle this problem. I have anxiety about performance when I block in the database (I think about trigger or constraints or transaction)</p>
  <hr />
  <p><em>Additional:</em> I have created a trigger, it will fire before creating a new invoice, it will check the invoice number has already available or not, and it worked, but I hope that will have a better solution (base on availability technology), b/c I don't want have to check each insert request.</p>