知道當您需要從其他線程更新gui時使用Invoke方法。但是我怎樣才能實現這個沒有綁定控制代碼?從線程C#更新GUI,無需綁定到UI控件
這裏是我的測試類:
class test
{
public List<Thread> threads = new List<Thread>();
public int nThreads = 0;
public int maxThreads = 5;
public void DoWork(object data)
{
string message = (string)data;
//MessageBox.Show(message);
}
public void CreateThread(object data)
{
if (nThreads >= maxThreads)
return;
Thread newThread = new Thread(DoWork);
threads.Add(newThread);
newThread.IsBackground = true;
newThread.Start(data);
nThreads++;
}
public void WindUpThreads()
{
//MessageBox.Show("count: " + nThreads.ToString());
for(int i = 0; i < threads.Count; i++)
{
if (threads[i].IsAlive == false)
{
threads[i].Abort();
threads.RemoveAt(i);
//MessageBox.Show("removing at " + i.ToString());
}
}
nThreads = threads.Count;
}
}
問題是= I必須按順序使用什麼tecnique更新GUI而不是硬編碼控制成class?我嘗試將代理傳遞給DoWork方法,但這不起作用(http://pastebin.com/VaSYFxPw)。謝謝!
我使用的WinForms,.NET 3.5
這裏的button_click處理程序:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
test thTest = new test();
string[] strings;
try
{
strings = File.ReadAllLines("C:\\users\\alex\\desktop\\test.txt");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
bool flag = true;
int counter = 0;
int dataCount = strings.Length;
while (flag == true)
{
if (counter >= dataCount)
{
flag = false;
}
while (thTest.nThreads < thTest.maxThreads)
{
if (flag == false)
break;
thTest.CreateThread(strings[counter]);
//Data d = new Data();
//d.deleg = AddItem;
//d.mess = strings[counter];
//thTest.CreateThread((object)d);
//MessageBox.Show(counter.ToString());
counter++;
}
thTest.WindUpThreads();
if (flag == false)
{
do
{
thTest.WindUpThreads();
} while (thTest.nThreads != 0);
}
}
listBox1.Items.Add("Done");
}
的想法是,我'啓動線程我要處理的每個任務。在我檢查完成任務後,他們將被關閉,並啓動新的任務,直到不再有任務完成。
每個List <>都有一個.Count屬性,你可以用它來代替nThreads。在for循環中,您從列表中刪除項目。這可能是有問題的。想象一下包含2個項目的列表。循環以i = 0開始,然後刪除第0項。現在列表只有1個項目,當它試圖訪問列表[1]時,它將失敗。 –
你使用什麼樣的框架?的WinForms? WPF? ...? –
@DennisKuypers,但我已經在使用.Count。或者你是什麼意思? –