Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
What is the best way to make a C# SortedList thread-safe?

I need a data structure with O(log n) retrieval and O(1) lookup by index. So SortedList is the obvious choice.

Now I want to know the best way to make its methods thread-safe? Here is a partial implementation using lock, but I am wondering if there is a more efficient way? For example, if there were an immutable SortedList I could use that, but I can only see SortedDictionary offered as immutable.

public class ConcurrentSortedList<TKey, TValue>
{
    private object _locker = new object();
    private SortedList<TKey, TValue> _list = new SortedList<TKey, TValue>();

    public void Add(TKey key, TValue value)
    {
        lock(_locker)
        {
            _list.Add(key, value);
        }
    }

    public TValue GetByIndex(int index)
    {
        lock(_locker)
        {
            return _list.Values[index];
        }
    }
}

Edit. As pointed out below by @Theodor, getting by index seems useless in a multi-threaded environment, and I agree then that there is no point in trying to make SortedList tread-safe.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!