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.
7,593 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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.
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);
}
}