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?