I am not that good in multithreading. But this is what I need to do.
I have a datagrid. I want one method to fill the datagrid with only first 50 rows. In the mean time I want a thread to fetch the next 20 rows and update the datatable so that when the 50 rows has been displayed the next 20 rows gets attached to the datatable object. In this way I can work huge amount of data without making my datatable go slow. But I am stuck with resource sharing (sharing the datatable object) in multithreading.
The have the code below
public partial class InsertAndUpdateData : Window
{
DataTable dt = new DataTable();
public object lockOn = new object();
public InsertAndUpdateData()
{
InitializeComponent();
Thread oThread = new Thread(new ParameterizedThreadStart(FillGrid));
oThread.Start(dt);
oThread.Join();
Thread.Sleep(1000);
oThread.Abort();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string name = txtName.Text;
int salary = Convert.ToInt32(txtSalary.Text);
using (var context = new NewtonEntities())
{
Employee emp = new Employee();
emp.name = name;
emp.salary = salary;
context.AddToEmployees(emp);
context.SaveChanges();
}
FillGridLastRowInserted();
}
public void FillGrid(object dtx)
{
lock (lockOn)
{
dt = (DataTable)dtx;
var db = new NewtonEntities();
var dataTable = (from c in db.Employees
select new
{
c.id,
c.name,
c.salary
}).Take(20);
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("salary", typeof(int));
foreach (var item in dataTable)
{
DataRow dr = dt.NewRow();
dr["id"] = item.id;
dr["name"] = item.name;
dr["salary"] = item.salary;
dt.Rows.Add(dr);
}
myGrid.ItemsSource = dt.DefaultView;
}
}
public void FillGridLastRowInserted()
{
var db = new NewtonEntities();
var dataTable = (from c in db.Employees
orderby c.id descending
select new
{
c.id,
c.name,
c.salary
}).First();
DataRow dr = dt.NewRow();
dr["id"] = dataTable.id;
dr["name"] = dataTable.name;
dr["salary"] = dataTable.salary;
dt.Rows.Add(dr);
myGrid.ItemsSource = dt.DefaultView;
}
}
I have a datatable in the main class. I want the dt object to be shared by two threaded methods.
But every time I am hit with the following error.