0

I was trying to add dynamic rows to a GridView using below variable.

private static ThreadLocal<List<Product>> productList = null;

Below is the event handler adding the rows dynamically.

protected void Button1_Click(object sender, EventArgs e)
{

            if (productList == null || productList.Value == null)
            {

                productList = new ThreadLocal<List<Product>>(() => new List<Product>());
            }
            productList.Value.Add(new Product { ProductID = 100, ProductName = "Product " + Thread.CurrentThread.Name, UnitPrice = 5000 });
            GridView1.DataSource = productList.Value;
            GridView1.DataBind();
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
}

public class Product
{
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public decimal UnitPrice { get; set; }
}

I am clicking the button for adding rows. Issue is that up to 5-6 rows, data is loading correctly, then again row became 1 and after that again appearing with multiple rows. So I am assuming threads are still crosscutting here and data is loosing in between, which is not expecting by using ThreadLocal<>. Any comments?

Blindy
  • 65,249
  • 10
  • 91
  • 131
Jaish Mathews
  • 766
  • 1
  • 9
  • 25
  • 1
    The code you've posted does not create any new threads, why are you using `ThreadLocal` ? – Lasse V. Karlsen Aug 15 '15 at 20:58
  • 2
    Can you explain what you're trying to do here? I have no idea why you're using thread local here. Threads in an ASP.NET application are from a pool. Using ThreadLocal is likely to cause unexpected behavior since sometimes it will use the same thread, other times it will pull a different thread from the pool. You need to explain what your desired outcome is so we can help you achieve it. – dmeglio Aug 15 '15 at 21:20
  • I was trying to add rows to a GridView in a button click. Each time, rows would append. So I am using a static variable to keep the current rows during a postback without depend on Session. I also don't want this static varibale to share acorss so that during post back, I won't loose rows. – Jaish Mathews Aug 16 '15 at 11:52

0 Answers0