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}");
}
@Markus Freitag I provided about as simple as you can get, Lazy is described here. If you have not read this you need to as me writing up what is written there serves nobody.
Since I exposed a list you have methods and properties which are always available without a singleton.
You're right, I haven't read it in detail yet. It just looks complicated. If I would only go via Lock, do I need one Lock or two Lock objects? Can you answer that please?
Thanks!
For what?
Never used locks like this so I can't say, only have used singleton and classes under System.Collections.Concurrent. Best guess is you need a lock on both and test for the possibilities for deadlocks. In any case I'd refactor as I've shown or similar.
Yes you are locking a single object, not the list I think.
Maybe you have another good example.
Sorry for asking again. I'm just looking for a good and workable solution.
I hope you understand what I want. Do you?
Sign in to comment