Question: Can someone look at my select statement and offer some help? I have a field that has a whole number value that I need to convert to a decimal and depending on if that value is > 0 or not, then do some more math to ultimately get the discounted cost after the discount percent is taken off. The problem is it wants to put the discount field into my group by clause which I do not want since it then will group the discounted ones seperate from the not discounted ones. Hopefully this makes sense. Here is the statement.

```
SELECT CASE 
            WHEN ITEMS.DISCOUNT > 0 THEN 
                (
                     SUM(ITEMS.IT_UNLIST * QUANTS) 
                     - SUM(ITEMS.IT_UNLIST * QUANTS) 
                     * CAST((ITEMS.DISCOUNT/100) as DECIMAL(8,2))
                 )
            ELSE 
                SUM(ITEMS.IT_UNLIST * QUANTS) 
        END AS Sales
        , MONTH(ITEMS.IT_SDATE) AS Mnth
        , CUST.STATE

```

I group by Mnth, then by State and thats all I want to group by. I am pretty new to sql so any advice would be appreciated. Any thoughts?

Answer: 
Use the mult-thread controle `lock`. This prevents that your code will be run more the one time in same moment.

**EDITED**  

EXAMPLE:

```
public class Foo
{
    private static object _lockKey = new object();

    private void YourEventHandlerMethod(object sender, EventArgs e)
    {   
        lock (_lockKey)
        {
            // the code you put inside this block will be execute only
            // once at time.

            // If a second call has the intention to use this block before
            // the conclusion of the first call, the second call (the thread)
            // will be put in hold.
        }
    }
}

```
Eight years down the road, I've discovered the joy of the blocking collection.

Instead of having the event handler do the work, I could have just put some data in a blocking collection and had a separate thread to work that.

```cs
private readonly BlockingCollection<Whatever> queue = new BlockingCollection<Whatever>();

Task.Run(() =>
{
  while (!queue.IsCompleted) {

   // Do whatever

  }
}

// Then just add a bunch of stuff to it
queue.Add(new Whatever());

// It will just keep working the queue in a separate thread, going back for a new Whatever whenever it's done

// You can even start multiple threads to work the queue. They won't interfere with each other

```