下面是一个示例代码,演示如何使用 C# 连接多个 S7 PLC 并使用字典存储每个连接。每个连接都在一个单独的线程中进行独立写入。

using System;
using System.Collections.Generic;
using System.Threading;

namespace S7PLCConnection
{
    class Program
    {
        static Dictionary<string, Thread> plcThreads = new Dictionary<string, Thread>();

        static void Main(string[] args)
        {
            // 添加需要连接的PLC
            AddPLCConnection('PLC1', '192.168.0.1');
            AddPLCConnection('PLC2', '192.168.0.2');

            // 启动所有PLC连接
            StartAllPLCConnections();

            // 等待所有线程完成
            foreach (var thread in plcThreads.Values)
            {
                thread.Join();
            }

            Console.WriteLine('所有PLC连接已完成。');
            Console.ReadLine();
        }

        static void AddPLCConnection(string plcName, string ipAddress)
        {
            Thread thread = new Thread(() =>
            {
                // 创建PLC连接
                S7PLCConnection connection = new S7PLCConnection(ipAddress);

                // 在此处进行PLC写入操作
                // connection.Write(...);

                Console.WriteLine('PLC连接 {0} 已完成。', plcName);
            });

            plcThreads.Add(plcName, thread);
        }

        static void StartAllPLCConnections()
        {
            foreach (var thread in plcThreads.Values)
            {
                thread.Start();
            }
        }
    }

    class S7PLCConnection
    {
        private string ipAddress;

        public S7PLCConnection(string ipAddress)
        {
            this.ipAddress = ipAddress;
        }

        // 在此处添加PLC写入方法
        // public void Write(...) { ... }
    }
}

在示例代码中,我们首先创建了一个plcThreads字典,用于存储PLC连接的线程。然后,我们通过AddPLCConnection方法添加需要连接的PLC,其中包括PLC名称和IP地址。

AddPLCConnection方法中,我们创建了一个新的线程,并将其添加到plcThreads字典中。每个线程都包含了需要在PLC上进行的写入操作。

最后,我们通过调用StartAllPLCConnections方法来启动所有的PLC连接线程。然后,我们使用Join方法等待所有线程完成。

请注意,在示例代码中的S7PLCConnection类中,我们只是简单地将PLC连接的IP地址存储在了一个私有字段中。您需要根据您的实际需求来实现PLC写入方法。


原文地址: https://www.cveoy.top/t/topic/qnWm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录