mofidul mofidul - 3 months ago 18
C# Question

Can't return DataTable with thread

I'm trying to return DataTable from another class using thread...But the thread is not returning the Datable...while not used thread its work fine.

public class reatail
{
DataTable order_dt = new DataTable();
public DataTable loadAllOrder()
{

OleDbConnection co = new OleDbConnection();
co.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sd + "bowoni.accdb";
string loadAll = "select * from allorder";
co.Open();
OleDbCommand cc = new OleDbCommand(loadAll, co);
OleDbDataAdapter ad = new OleDbDataAdapter(cc);
ad.Fill(order_dt);
return order_dt;
}
}



public partial class RecieveOrder : Form
{

DataTable dy = new DataTable();
reatail r = new reatail();
Thread t;
public void storeToStock()
{
//DataTable dy = new DataTable();
Thread th=new Thread(()=>dy=r.loadAllOrder());
th.Start();
foreach(DataRow row in dy.Rows)
{
MessageBox.Show(row[0].ToString());
}
}
}

RBT RBT
Answer

You are trying to access the return value even before your thread has finished executing. You need to do th.Join(); before starting to iterate the rows in the table using foreach loop. Here is how you can do it:

public partial class RecieveOrder : Form
{

    DataTable dy = new DataTable();
    reatail r = new reatail();
    Thread t;
    public void storeToStock()
    {
        //DataTable dy = new DataTable();
        Thread th=new Thread(()=>dy=r.loadAllOrder());
        th.Start();
        //wait for the thread to finish its execution and get the data from backend DB.
        th.Join();
        //now iterate the rows retrieved from DB
        foreach(DataRow row in dy.Rows)
        {
            MessageBox.Show(row[0].ToString());
        }
    }
}
Comments