views:

137

answers:

2

My program has a static list of type classA. ClassA implements a threading timer that executes a task. The list may contain as many instances of classA as desired. Is this technique causing threading issues where the class instances can block each other? It that is the case how can I solve the that problem. ex:

static List<MyClassType> list=null;
void static Main()
{
   list = new List<MyClassType>();
   var a = new MyClassType();
   var b = new MyClassType();
   list.Add(a);
   list.Add(b);
   Console.ReadKey();
}

a and b will execute theire internal task based on the timer.Is it s bsd technique? Why?

+3  A: 

It really depends on what the timer tasks do. Just because there are references to various objects from the same list doesn't affect how their threads are scheduled etc.

It would be unsafe if the timer action started mutating the list - List<T> isn't thread-safe beyond multiple readers. If one of the parts of the timer task needs to remove the instance from the list (for example) then you'll need locking to make that work appropriately - and you'll also need to be careful when iterating over the list, etc.

Jon Skeet
A: 

The code is not thread-safe, if thats what you mean.

If methods like add and remove are called from the threads and they are called at the same time it will cause your list to break.

You can solve this by using lock(list){ list.add(); list.remove(); } every time you use the list.

But that's messy because you might forget... A much better solution is to override the List class and make your own safe implementation of it:

public class ThreadSafeList<T> : List<T>
{
    private List<T> list;
    // Use any normal List constructor here.
    public ThreadSafeList(List<T> list)
    {
        this.list = list;
    }

    public bool Add(T item)
    {
        lock (list)
        {
            return this.Add(item);
        }
    }
}

And of course also implement the remaining methods, use lock on the ones that might change anything in the List.

MrFox