你好,這是我的多線程代碼,它工作正常使用參數化功能的線程在C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
namespace searchIpAdresses
{
public partial class frmSearchIpRange : Form
{
public frmSearchIpRange()
{
InitializeComponent();
}
int intStartIp, intEndIp;
private void frmSearchIpRange_Load(object sender, EventArgs e)
{
startIp.Text = "0.0.0.0";
endIp.Text = "0.1.0.0";
nudThreads.Value = 1;
}
private bool calcIpAddressRange()
{
intStartIp = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(startIp.Text).GetAddressBytes(), 0));
intEndIp = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(endIp.Text).GetAddressBytes(), 0));
if (intStartIp>intEndIp)
{
MessageBox.Show("End Ip must be bigger than Begin Ip!");
return false;
}
else
{
return true;
}
}
private void btnShow_Click(object sender, EventArgs e)
{
if (calcIpAddressRange())
{
int threadCount = Convert.ToInt32(nudThreads.Value);
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(new ThreadStart(getPerformance));
threads[i].Name = string.Format(i.ToString());
}
foreach (Thread t in threads)
{
t.Start();
}
//for (int i = 0; i < nudThreads.Value; i++)
//{
// if (threads[i].IsAlive)
// threads[i].Abort();
//}
}
}
private void getPerformance()//int sampleStartIp, int sampleEndIp
{
if (calcIpAddressRange())
{
lbAddress.Items.Clear();
progressBar1.Maximum = intEndIp - intStartIp;
int i;
for (i = intStartIp; i < intEndIp; i++)
{
string ipAddress = new IPAddress(BitConverter.GetBytes(IPAddress.NetworkToHostOrder(i))).ToString();
progressBar1.Value++;
lbAddress.Items.Add(ipAddress);
}
MessageBox.Show(i.ToString() + " addresses added", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
progressBar1.Value = 0;
}
}
}
}
,但我想在getPerformance功能拆分工作。所以我在這種情況下,Visual Studio中使用它像
threads[i] = new Thread(new ThreadStart(getPerformance(sampleStart, sampleEnd)))
等給了我錯誤「預期的方法名」。解決辦法是什麼 ?
編輯:我試過,但我想不出它適應陣列格式工作@Henk Holterman
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
//threads[i] = new Thread(new ThreadStart(getPerformance));
threads[i].Name = string.Format(i.ToString());
Thread t = new Thread(() => getPerformance(intStartIp, intEndIp));
}
foreach (Thread t in threads)
{
t.Start();
}
平臺,語言?它看起來像C#,但提到它是一個很小的努力。 – 2010-08-15 09:40:57
抱歉,我忘了它,現在編輯.. – Rapunzo 2010-08-15 10:50:18
getPerformance將在非ui線程上執行,因此對progressBar1的更改將不起作用。此外,多個線程可能會同時更改屬性,使得粘貼的代碼容易出現線程問題。 – sisve 2010-08-15 11:27:10