线程问题(线程间操作无效: 从不是创建控件“results”的线程访问它。)
private void button1_Click(object sender, EventArgs e)
{
results.Items.Clear();
string addr = address.Text;
Object state = new Object();
OnResovled = new AsyncCallback(Resolved);
Dns.BeginResolve(addr, OnResovled, state);
}
private void Resolved(IAsyncResult ar)
{
string buffer;
IPHostEntry iphe = Dns.EndResolve(ar);
buffer = "Host name:" + iphe.HostName;
results.Items.Add(buffer);
foreach (string alias in iphe.Aliases)
{
buffer = "Alias:" + alias;
results.Items.Add(buffer);
}
foreach (IPAddress addrs in iphe.AddressList)
{
buffer = "Address:" + addrs.ToString();
results.Items.Add(buffer);
}
}
运行报错:线程间操作无效: 从不是创建控件“results”的线程访问它。
------解决方案--------------------
------解决方案--------------------C# code
private void Resolved(IAsyncResult ar)
{
if (this.InvokeRequired)
{
OnResovled = new AsyncCallback(Resolved);
this.Invoke(OnResovled , new object[] { ar});
}
else
{
string buffer;
IPHostEntry iphe = Dns.EndResolve(ar);
buffer = "Host name:" + iphe.HostName;
results.Items.Add(buffer);
foreach (string alias in iphe.Aliases)
{
buffer = "Alias:" + alias;
results.Items.Add(buffer);
}
foreach (IPAddress addrs in iphe.AddressList)
{
buffer = "Address:" + addrs.ToString();
results.Items.Add(buffer);
}
}
}