2

I am using .net 3.0. How can I make sure is threadsafe - AddRange

public class GetItems
{
    List<Item> items = new List<Item>();
    string p1;
    string p2;

    public List<Item> Get(string para1, string para2)
    {
        p1 = para1;
        p2 = para2;

        ThreadStart ts1 = new ThreadStart(Add1);
        ThreadStart ts2 = new ThreadStart(Add2);

        Thread th1 = new Thread(ts1);
        Thread th2 = new Thread(ts2);

        try
        {
            Monitor.Enter(items);

            th1.Start();
            th2.Start();

            th1.Join();
            th2.Join();
        }
        finally
        {
            Monitor.Exit(items);
        }
        return items;
    }
    private void Add1()
    {
        items.AddRange(C1.GetItems(p1, p2));
    }
    private void Add2()
    {
        items.AddRange(C2.GetItems(p1, p2));
    }
}

2 Answers 2

3

Do you need to spawn a new thread to call Add2()?

The easiest way to make it threadsafe is to not spawn a new thread just to call Add2().

Instead, call Add1() and then call Add2() using the same thread.

2
  • 2
    Considering that a simple lock on an object here will make those two run sequentially anyway, this seems to be the best advice. Unless the actual production methods does more, there doesn't seem to be any point to threading it at all. Perhaps GetItems needs to run in the background? Mar 15, 2011 at 18:50
  • Correct answer for a question with an unrealistic example. Mar 15, 2011 at 18:55
2

Use the lock statement.

http://msdn.microsoft.com/en-us/library/c5kehkcz(v=VS.100).aspx

EX. :

Object obj = new Object();
private void Add1()
{ 
  lock(obj)
  {
    items.AddRange(C1.GetItems(p1, p2)); 
  }
} 
private void Add2() 
{ 
  lock(obj)
  {
    items.AddRange(C2.GetItems(p1, p2)); 
  }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.