C# 连接到多个设备
我有14个不同的设备,我需要同时建立连接,每隔几分钟重新检查连接状态 我想知道我是否需要为它们中的每一个制作一个线程,或者是否有更好的方法来完成它C# 连接到多个设备,c#,telnet,tcpclient,C#,Telnet,Tcpclient,我有14个不同的设备,我需要同时建立连接,每隔几分钟重新检查连接状态 我想知道我是否需要为它们中的每一个制作一个线程,或者是否有更好的方法来完成它 public partial class Automation : Form { public Automation() { InitializeComponent(); } //==========================================
public partial class Automation : Form
{
public Automation()
{
InitializeComponent();
}
//======================================================================
TelnetConnection Telnet1 = new TelnetConnection("10.10.100.21", 9090);
TelnetConnection Telnet2 = new TelnetConnection("10.10.100.22", 9090);
TelnetConnection Telnet3 = new TelnetConnection("10.10.100.23", 9090);
TelnetConnection Telnet4 = new TelnetConnection("10.10.100.24", 9090);
TelnetConnection Telnet5 = new TelnetConnection("10.10.100.25", 9090);
TelnetConnection Telnet6 = new TelnetConnection("10.10.100.26", 9090);
TelnetConnection Telnet7 = new TelnetConnection("10.10.100.27", 9090);
//======================================================================
TelnetConnection ADV1 = new TelnetConnection("10.10.100.1", 9090);
TelnetConnection ADV2 = new TelnetConnection("10.10.100.2", 9090);
TelnetConnection ADV3 = new TelnetConnection("10.10.100.3", 9090);
TelnetConnection ADV4 = new TelnetConnection("10.10.100.4", 9090);
TelnetConnection ADV5 = new TelnetConnection("10.10.100.5", 9090);
TelnetConnection ADV6 = new TelnetConnection("10.10.100.6", 9090);
TelnetConnection ADV7 = new TelnetConnection("10.10.100.7", 9090);
//======================================================================
private void Automation_Load(object sender, EventArgs e)
{
//===========Check Online State===========//
Check_Online_Offline_State();
//===========Check Online State===========//
}
}
此外,我将在需要时发送每个设备命令
但是telnet连接的问题是,因为它们在3次连接后会出现异常,但如果我只运行ADV,则会建立连接
建议?使用Parallel.ForEach,它是异步多线程,代码更少,只需示例:
private TelnetConnection[] m_Connections;
...
m_Connections = new TelnetConnection[50];
for (var i = 0; i < m_Connections.Length; i++)
{
m_Connections[i] = new TelnetConnection(string.Concat("10.10.100.", i), 9090);
}
...
Parallel.ForEach(m_Connections, conn =>
{
bool isAlive = conn.IsHostAlive();
});
private TelnetConnection[]m_连接;
...
m_Connections=新的TelnetConnection[50];
对于(var i=0;i
{
bool isAlive=conn.IsHostAlive();
});
我还需要能够在不同的时间向他们每个人发送命令,您可以自己扩展它。这是唯一的例子,使用多线程和更少的键入。“他们遇到异常”-什么异常?如果其中一个IP不在线或无法访问,程序将根本无法加载