C# - lock object - the correct way to use it.

Markus Freitag 3,786 Reputation points
2020-12-11T10:18:37.003+00:00

Hello,

I am adding and removing items in a list. This can be done by two threads in the same program.

The questions are
Is one lock element enough or are two necessary?

static object LockPackageList = new object();

// or 

static object LockPackageListInsert = new object(); 
static object LockPackageListDelete = new object();

For deleting and adding.

[XmlRoot("PACKAGELABEL")]
public class PackageLabel
{     
     [XmlAttribute("quantityPackage")]
     public int QuantityPackage { get; set; }

     [XmlAttribute("batchNumber")]
     public string BatchNumber { get; set; }

public void PackageInsert(PackageLabel currentPackage, LType type = LType.FiFo)
{
    lock (LockPackageList)
    {
        switch (type)
        {
            case LType.FiFo:
                ListPackageLabel.Add(currentPackage);
                // BlockingCollectionPackageLabel.Add(currentPackage);
                break;
            case LType.LiFo:
                ListPackageLabel.Insert(0, currentPackage);
                break;
        }
    }
}

public void TestDelete()
{
    CurrentPackageLabel = ListPackageLabel[0];

    // ** 11.12.2020 every time the first element.
    lock (LockPackageList)
    {
        ListPackageLabel.RemoveAt(0);
    }

I think that's the easiest way, if that works.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,207 questions
0 comments No comments
{count} votes

Accepted answer
  1. Sardou Noureddine 241 Reputation points
    2020-12-11T17:29:54.557+00:00

    Hi @Markus Freitag

    You need to use only one lock on all actions accessing or modifying the list.
    And instead of having the lock containing all the switch block, surround only the add method:

    public void PackageInsert(PackageLabel currentPackage, LType type = LType.FiFo)  
    {  
         switch (type)  
         {  
             case LType.FiFo:  
                 lock (LockPackageList)   
                 {  
                      ListPackageLabel.Add(currentPackage);  
                 }  
                 break;  
             case LType.LiFo:  
                 lock (LockPackageList)   
                 {  
                     ListPackageLabel.Insert(0, currentPackage);  
                 }  
                 break;  
             }  
     }  
          
     public void TestDelete()  
     {  
         // ** 11.12.2020 every time the first element.  
         lock (LockPackageList)  
         {  
             CurrentPackageLabel = ListPackageLabel[0];  
             ListPackageLabel.RemoveAt(0);  
         }  
    }  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful