看看我的密码。
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必须像旧线程项一样继续(即下一个标识符将是[4]、[5]、[6]等)。
我不担心这个错误:
//Debug when ButtonClick2 is running
connect_thread = Error: Index was outside the bounds of the array.因为我可以使用dataGridView1.Rows.Count创建一个线程列表,它可以正常工作。但是,我希望以另一种方式来做,因为当用户向dataGridView中添加更多数据时,索引将再次出错。
如何在保留识别码的同时将新线程添加到线程数组的末尾?
发布于 2015-09-25 14:28:29
只需尝试用如下所示的列表替换数组:
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();
}
}发布于 2015-09-25 14:29:28
由于您有一个具有定义大小的数组,因此它不是为数组定义新大小的好方法。相反,您可以使用一个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();
}发布于 2015-09-25 14:57:12
为了便于讨论,请使用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++;至于其余的问题,我不太清楚到底是什么问题。
https://stackoverflow.com/questions/32784318
复制相似问题