寻求一般帮助理解这个程序流程: 在窗户那为什么当我调用一个新的线程中的一个方法,该线程不构成应用在继续执行之前等待该方法完成?方法称为线程中意外顺序(C#.NET)执行
默认情况下异步执行的线程中调用的方法? (我希望程序阻塞,直到方法完成而不必使用下面的Thread.Sleep行)。下面的“Thread.Sleep”一行的评论可能有助于进一步澄清我的问题。 - 谢谢!
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)
}
内容的 “ThreadSafeCalls” 类:
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;
}
}
你确实需要为我们提供[mcve]。我试图复制你的问题,但不能。代码中可能会出现一些我们无法看到的情况。 – Enigmativity