我有14个不同的设备,我需要在同一时间和每隔几分钟建立一个连接,以重新检查连接状态。
我想知道我是否需要为每一个创建一个帖子,或者是否有更好的方法来做它。
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,它会建立一个连接正常。
建议?
答案 0 :(得分:1)
使用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();
});