C# List - list can be filled or taken from two threads

Markus Freitag 3,786 Reputation points
2020-12-10T12:58:36.933+00:00

Hello,

static object LockPackageList = new object();

void Test1()
{    
    lock (LockPackageList)
    {
     switch (type)
     {
     case L.FiFo:
     ListPackageLabel.Add(currentPackage);
     // BlockingCollectionPackage.Add(currentPackage);
     break;
     case L.LiFo:
     ListPackageLabel.Insert(0, currentPackage);
     break;
     }
    }
}

public void DeletePackage()
        {
            lock (LockPackageList)
            {
                ListPackageLabel.RemoveAt(0);
            }

Is that sufficient with the lock?

Need I one static object LockPackageList = new object();
or two?
For Add and Remove?

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,306 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,196 Reputation points
    2020-12-10T13:33:47.923+00:00

    Hello @Markus Freitag

    Have you considered using a thread-safe Singleton? The following is based off this web page sixth version.

    public class Address  
    {  
        public string Type { get; set; }  
        public string Company { get; set; }  
        public string Number { get; set; }  
        public string Street { get; set; }  
        public string City { get; set; }  
    }  
    
    public partial class Person  
    {  
        public int Id { get; set; }  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public DateTime? DateOfBirth { get; set; }  
        public IList<Address> Addresses { get; set; }     
    }  
    

    Singleton

    public sealed class Sample  
    {  
        private static readonly Lazy<Sample> Lazy =  
            new Lazy<Sample>(() =>  
                new Sample());  
      
        /// <summary>  
        /// Entry point to access information in this class  
        /// </summary>  
        public static Sample Instance => Lazy.Value;  
        public List<Person> People { get; set; }  
      
        private Sample()  
        {  
            People = new List<Person>();  
        }  
    }  
    

    Add in one thread

    Sample.Instance.People.Add(new Person() {FirstName = "Karen", LastName = "Payne"});  
    

    Read in another thread (or add etc if you want)

    foreach (var person in Sample.Instance.People)  
    {  
        Console.WriteLine($"{person.FirstName} {person.LastName}");  
    }  
    

0 additional answers

Sort by: Most helpful