Tuncaf
Tuncaf

Reputation: 231

GenericList usage with different threads

I would like to ask that thing about generic list usage with different threads, there are generic list objects I have, and at the same time different threads may add, remove,get, or update that list. I try to handle that situation with code below. Is that ok ? or am I missing something?

public static TSource FirstOrDefaultThreadSafe<TSource>(this List<TSource> source, Func<TSource, bool> predicate) where TSource:new()
    {
        TSource result=new TSource();
        lock (source)
        {
            result = source.FirstOrDefault(predicate);                
        }       
        return result;
    }




public static void AddThreadSafe<T>(this List<T> sourceList, T item)
    {
        lock (sourceList)
        {
            sourceList.Add(item);               
        }
    }

Upvotes: 0

Views: 48

Answers (1)

Kim Ryunghi
Kim Ryunghi

Reputation: 66

Yes. That'll be fine. Let me give some advice to you, If generinc list more frequently read(find or get operation) than write(add or update operation), use read-write lock. That'll more efficient and more strategically.

Upvotes: 2

Related Questions