seeking general help in understanding this program flow: In a windows forms application why is it that when I call a method within a new thread that the thread doesn't wait for the method to complete before continuing execution?
Are methods called within a thread executed asynchronously by default? (I would expect the program to block until the method is complete without having to use the Thread.Sleep line below). The comment on the "Thread.Sleep" line below may help to clarify my question further. - Thank you!
private void button1_Click(object sender, EventArgs e)
{
//Call doStuff in new thread:
System.Threading.Thread myThread;
myThread = new System.Threading.Thread(new System.Threading.ThreadStart(doStuff));
myThread.Start();
}
private void doStuff()
{
//Instantiate external class used for threadSafe interaction with UI objects:
ThreadSafeCalls tsc = new ThreadSafeCalls();
int indx_firstColumn = 0;
//Loop 3 times, add a row, and add value of "lastRowAdded" to column1 cell.
for (int a = 0; a < 3; a += 1)
{
tsc.AddGridRow(dataGridView1); //Call method to add a row to gridview:
Thread.Sleep(1000); // Why does the execution of the line above go all crazy if I don't pause here? It's executing on the same thread, shouldn't it be synchronous?
tsc.AddGridCellData(dataGridView1,indx_firstColumn, tsc.lastRowAdded,tsc.lastRowAdded.ToString()); //Add value of "lastRowAdded" (for visual debugging)
}
Content of the "ThreadSafeCalls" class:
public int lastRowAdded = -999;
public void AddGridRow(DataGridView gv)
{
if (gv.InvokeRequired)
{
gv.BeginInvoke((MethodInvoker)delegate ()
{
lastRowAdded = gv.Rows.Add();
});
}
else
{
lastRowAdded = gv.Rows.Add();
}
}
public void AddGridCellData(DataGridView gv, int column, int rowID, string value)
{
//Thread safe:
if (gv.InvokeRequired)
{
gv.BeginInvoke((MethodInvoker)delegate () { gv.Rows[rowID].Cells[column].Value = value + " "; });
}
else
{
gv.Rows[rowID].Cells[column].Value = value;
}
}