Such a scenario: a certain amount of data to be inserted in a table,when reaches a threshold no longer insert, I simulated this scenario, in the case of multi-threaded (eg asp.net) appeared concurrent problems.

My question is how to solve of the concurrent problem, do not use the lock case

void Main()
{

   Enumerable.Range(0,20).ToList().ForEach(i=>{
       MockMulit();
   });

}
//Start a certain number of threads for concurrent simulation
void MockMulit()
{
  int threadCount=100;

  ClearData();//delete all data for test


  var tasks=new List<Task>(threadCount);
  Enumerable.Range(1,threadCount).ToList().ForEach(i=>{
     var j=i;
     tasks.Add(Task.Factory.StartNew(()=>T3(string.Format("Thread{0}-{1}",Thread.CurrentThread.ManagedThreadId,j))));
  });
  Task.WaitAll(tasks.ToArray());

  CountData().Dump();//show that the result
}

method one - concurrency very serious

void T1(string name)
{
        using(var conn=GetOpendConn())
        {
            var count=conn.Query<int>(@"select count(*)  from dbo.Down").Single();
            if(count<20)
            {
                conn.Execute(@"insert into dbo.Down (UserName) values (@UserName)",new{UserName=name});
            }
        }

}

method two - put the sql together can reduce concurrent, but still exist

void T2(string name)
{
   using(var conn=GetOpendConn())
   {
       conn.Execute(@"
                      if((select count(*)  from dbo.Down)<20)
                        begin
                          --WAITFOR DELAY '00:00:00.100';
                          insert into dbo.Down (UserName) values (@UserName)
                        end",new{UserName=name});
   }
}

method three - with lock destroy the concurrent,but i don't think it is a best solution

private static readonly object countLock=new object();
void T3(string name)
{
    lock(cou
Edit
Report