I have an application that, before is creates a thread it calls the database to pull X amount of records. When the records are retrieved from the database a locked flag is set so those records are not pulled again.
Once a thread has completed it will pull some more records form that database. When I call the database from a thread should I set a lock on that section of code so it is called only by that thread at that time? Here is an exmaple of my code (I commented in the area where I have the lock):
private void CreateThreads() 
{ 
       for(var i = 1; i <= _threadCount; i++) 
    { 
        var adapter = new Dystopia.DataAdapter(); 
        var records = adapter.FindAllWithLocking(_recordsPerThread,_validationId,_validationDateTime); 
        if(records != null && records.Count > 0) 
        { 
            var paramss = new ArrayList { i, records }; 
            ThreadPool.QueueUserWorkItem(ThreadWorker, paramss);
        } 
        this.Update(); 
    } 
} 
private void ThreadWorker(object paramList) 
{ 
    try 
    { 
        var parms = (ArrayList) paramList; 
        var stopThread = false; 
        var threadCount = (int) parms[0]; 
        var records = (List<Candidates>) parms[1]; 
        var runOnce = false; 
        var adapter = new Dystopia.DataAdapter(); 
        var lastCount = records.Count; 
        var runningCount = 0; 
        while (_stopThreads == false) 
        { 
           if (records.Count > 0) 
            { 
                foreach (var record in records) 
                { 
                    var proc = new ProcRecords(); 
                    proc.Validate(ref rec); 
                    adapter.Update(rec);
                    if (_stopThreads) 
                    { 
                        break; 
                    } 
                } 
                //This is where I think I may need to sync the threads.
                //Is this correct?
                lock(this){
                records = adapter.FindAllWithLocking;  
                }             
            } 
        } 
    } 
    catch (Exception ex) 
    { 
        MessageBox.Show(ex.Message); 
    } 
SQL to Pull records:
WITH cte AS ( 
  SELECT TOP (@topCount) *
  FROM Candidates WITH (READPAST) 
  WHERE 
  isLocked = 0 and
  isTested = 0 and  
  validated = 0 
  ) 
UPDATE cte 
  SET 
  isLocked = 1,
  validationID = @validationId,
  validationDateTime = @validationDateTime
  OUTPUT INSERTED.*;
 
     
     
     
    