gpt4 book ai didi

c# - 使用 backgroundworker 控件获取 lan 上的 ip 地址

转载 作者:行者123 更新时间:2023-11-30 21:20:27 25 4
gpt4 key购买 nike

我想从一个大局域网中获取事件或死亡的 ip 地址。但这需要很多次。我决定在这里使用 backgroundworker 是我的代码:

try
{

this.Status.Text = "Collecting Information...";

if(this.TxtWorkGroup.Text.Trim() == "")
{
MessageBox.Show("The Work Group name Should Not be Empty");
return;
}


// Use Your work Group WinNT://&&&&(Work Group Name)
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + this.TxtWorkGroup.Text.Trim());
DomainEntry.Children.SchemaFilter.Add("computer");


// To Get all the System names And Display with the Ip Address
foreach(DirectoryEntry machine in DomainEntry.Children)
{
string[] Ipaddr = new string[3];
Ipaddr[0] = machine.Name;


System.Net.IPHostEntry Tempaddr = null;

try
{
Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(machine.Name);
}
catch(Exception)
{
//MessageBox.Show("Unable to connect woth the system :" + machine.Name );
deadHostList.Items.Add(machine.Name);
continue;
}
System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
foreach(IPAddress TempA in TempAd)
{
Ipaddr[1] = TempA.ToString();

byte[] ab = new byte[6];
int len = ab.Length;

// This Function Used to Get The Physical Address
int r = SendARP( (int) TempA.Address, 0, ab, ref len );
string mac = BitConverter.ToString( ab, 0, 6 );

Ipaddr[2] = mac;
}

System.Windows.Forms.ListViewItem TempItem = new ListViewItem(Ipaddr);

this.ListHostIP.Items.Add(TempItem);
}

this.Status.Text = "Displayed";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error",System.Windows.Forms.MessageBoxButtons.OK );
Application.Exit();
}

但是当我尝试在 backgroundWorker1_DoWork 事件中使用这些代码时,它会给我错误消息

Cross-thread operation not valid: Control 'deadHostList' accessed from a thread other than the thread it was created on

如何修改我的代码?

最佳答案

正如 Chris 和 Reed 所说....您只能从创建控件的线程修改 Ui 控件...

您还可以使用 BackgroundWorker 的 ProgressChanged 事件进行 Ui 更新....

  var worker = new BackgroundWorker()
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};

/// runs on background thread
worker.DoWork += (s, e) =>
{
while (!done)
{
DoSomeWork();
// send a message to the Ui
// via the ProgressChanged event
worker.ReportProgress(percent, statusMessage);
}
};

/// the ProgressChanged event runs on the UI thread
worker.ProgressChanged += (s, e) =>
{
var msg = (MyStatusMessage)e.UserState;
someUiControl.Items.Add(msg.Text);
};

/// also runs on Ui thread
worker.RunWorkerCompleted += (s, e) =>
{

};

worker.RunWorkerAsync();

关于c# - 使用 backgroundworker 控件获取 lan 上的 ip 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3293077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com