【问题标题】:Connecting to multiple devices连接到多个设备
【发布时间】:2016-11-22 04:47:49
【问题描述】:

我有 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 次连接后遇到异常,但如果我只运行 advs,它就可以建立连接。

建议?

【问题讨论】:

  • “他们遇到了异常” — 什么异常?
  • 如果其中一个 IP 不在线或无法访问,则程序根本不会加载

标签: c# telnet tcpclient


【解决方案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();
  });

【讨论】:

  • 我还需要能够在不同的时间向他们每个人发送命令
  • 你可以自己扩展。这只是示例,使用多线程和更少的输入。
猜你喜欢
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2021-05-15
相关资源
最近更新 更多