在这里,我正在做一个检查用户名的过程。我创建了一个数据网格视图并从文本文件中加载了数据。所以 datagridview 在前两列中包含用户的名字和姓氏。我需要做的是逐行读取这些值,发现 first 和 last 没有相同的名称。这些操作在单独的类中执行。所以我需要从该类中获取结果并将结果显示给 gridview。当我只使用一个线程时,一切正常。但是,当我使用多个线程时,它只会在 gridview 阅读中引发出站异常。这是我的编码:
static int i, j=0, l=0,k=0,m=0;
public void check()
{
for (i = 0; i < dataGridView1.Rows.Count ; i++)
{
if (InvokeRequired)
{
Invoke(new UpdateDelegate(delegate
{
if (i == 0 && j==0)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "Status";
int colIndex = dataGridView1.Columns.Add(col);
dataGridView1.Rows[i].Cells[colIndex].Value = "Process Started";
j = 1;
}
else
{
dataGridView1.Rows[i].Cells[3].Value = "process Started";
}
}));
}
if (InvokeRequired)
{
Invoke(new UpdateDelegate(delegate
{
Process obj_reg = new Process(dataGridView1.Rows[i].Cells[1].Value.ToString(),dataGridView1.Rows[i].Cells[2].Value.ToString());
string res = obj_reg.register();
Thread.Sleep(500);
if (res.Contains("success"))
{
if (i == 0 && k==0)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "Result";
int colIndex = dataGridView1.Columns.Add(col);
dataGridView1.Rows[i].Cells[colIndex].Value = "Ya its different";
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
k = 1;
}
else
{
dataGridView1.Rows[i].Cells[4].Value = "Ya its different";
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
}
}
else
{
if (i == 0 && m == 0)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "Result";
int colIndex = dataGridView1.Columns.Add(col);
dataGridView1.Rows[i].Cells[colIndex].Value = "No its same";
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
m = 1;
}
else
{
dataGridView1.Rows[i].Cells[4].Value = "No its same";
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}
}
}));
}
}
}
public void Button1_Click(Object sender, EventArgs e)
{
Thread[] threads = new Thread[3];
for (int l = 0; l < 3; l++)
{
threads[l] = new Thread(new ThreadStart(check));
}
foreach (Thread t in threads)
{
t.Start();
}
}
请建议我如何在这里使用多线程......它只是一个例子..请解释任何其他方式..