This pattern seems to be working for me to achieve thread locking in this thread unsafe environment.
However in terms of patterns and best practice (especially as I have figured it out myself), I’m not overly mad on exposing two collections that collate the same results. But the unsafe collection does need to be exposed publically and I don’t want to make it private and have an ‘AddResult(x)’ method.
Is this the correct way to solve this problem?
public class UnsafeObject
{
public ObservableCollection<HighSpeedObject> ResultsUnsafe { get; set; }
/// Accessed by UI thread once every 100ms
public List<HighSpeedObject> Results
{
get
{
lock (_padlock)
{
return ResultsUnsafe.ToList();
}
}
}
private readonly static object _padlock = new object();
}
The instance of a
ObservableCollectionz<T>class is not thread safe, so your solution is not stable.The lock in the
Resultsproperty only ensures that one thread at a time can use that property, but it doesn’t protect theResultsUnsafeproperty. The other threads can change the collection in theResultsUnsafeproperty while theResultsproperty is creating a list from it.Side note: You are using a static member as identifier for a lock for non-static data. That means that the lock will prevent access in all instances of the class, not just the instance where the data is that you want to protect. To protect static data you should use a static member as identifier, and to protect instance data you should use an instance member as identifier.