看看我的代码。
Thread[] connect_thread;
public void thread_runned()
{
connect_thread = new Thread[dataGridView1.SelectedRows.Count];
for (int index = 0; index < dataGridView1.SelectedRows.Count; index++)
{
connect_thread[index] = new Thread(new ThreadStart(connect));
connect_thread[index].Start();
}
}
public void connect()
{
//performance code here
}
public void ButtonClick1()
{
//User select rows 0-4
thread_runned();
}
public void ButtonClick2()
{
//User select rows 5-9
thread_runned();
}
根据上面的代码,当我运行它,然后点击ButtonClick1
和ButtonClick2
时,它会返回两个不同的connect_thread
(有关详细信息,请参阅此调试。)
//Debug when ButtonClick1 is running
connect_thread = array(
[0] = System.Threading.Thread
[1] = System.Threading.Thread
[2] = System.Threading.Thread
[3] = System.Threading.Thread
)
//Debug when ButtonClick2 is running
connect_thread = Error: Index was outside the bounds of the array.
现在,我想在这个线程数组中添加一个新的线程项,但是indeces必须像旧的线程项一样继续(即,下一个indeces将是[4]
,[5]
,{{ 1}}等等。)
我不担心这个错误:
[6]
因为我可以使用//Debug when ButtonClick2 is running
connect_thread = Error: Index was outside the bounds of the array.
创建一个线程列表,它可以正常工作。但是,我希望以其他方式执行此操作,因为当用户向dataGridView1.Rows.Count
添加更多数据时,索引将再次出错。
如何在保留indeces的同时将新线程附加到我的线程数组的末尾?
答案 0 :(得分:3)
尝试使用以下列表替换您的数组:
List<Thread> connect_thread = new List<Thread>()
public void thread_runned()
{
for (int index = 0; index < dataGridView1.SelectedRows.Count; index++)
{
connect_thread.add(new Thread(new ThreadStart(connect)));
connect_thread[connect_thread.Count-1].Start();
}
}
答案 1 :(得分:3)
由于您有一个具有已定义大小的数组,因此为数组定义新大小并不是一个好的实践。相反,您可以使用List<Thread>
并添加所需的线程数量,用于示例:
List<Thread> connect_threads;
public void thread_runned()
{
int total = dataGridView1.SelectedRows.Count;
// define the array
connect_threads = new List<Thread>();
// define threads all threads on the list
for (int index = 0; index < total; index++)
connect_threads.Add(new Thread(new ThreadStart(connect)));
// start all threads on the list
foreach(var thread in connect_threads)
thread.Start();
// if you want to wait all the threads on the list to finish
foreach(var thread in connect_threads)
thread.Join();
}
答案 2 :(得分:1)
为了争论,请使用ThreadPool。
Int32 _ActiveThreadCount = 0;
delegate void SetTextCallback(String text);
public Int32 ActiveThreadCount
{
get
{
return _ActiveThreadCount;
}
set
{
_ActiveThreadCount = value;
SetText(value.ToString());
}
}
private void OnThreadCallback(Object state)
{
System.Threading.Thread.Sleep(1000);
ActiveThreadCount--;
}
private void SetText(String text)
{
if (label2.InvokeRequired)
{
SetTextCallback callback = new SetTextCallback(SetText);
this.Invoke(callback, text);
}
else
{
this.label2.Text = text;
}
}
使用
添加主题System.Threading.ThreadPool.QueueUserWorkItem(
new System.Threading.WaitCallback(OnThreadCallback), null);
ActiveThreadCount++;
至于其余部分,我不确定这里究竟是什么问题。