SOF User
SOF User

Reputation: 7830

threading in .net

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));
    }
}

Upvotes: 2

Views: 193

Answers (2)

Kipotlov
Kipotlov

Reputation: 518

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)); 
  }
} 

Upvotes: 2

ChrisNel52
ChrisNel52

Reputation: 15113

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.

Upvotes: 3

Related Questions