C# Windows service - Run two void methods

153 Views Asked by At

Can anyone help me with Windows service in C#? I used topshelf to create windows service. I have issue with run two methods together. When I run app via in console, it works. But when I try to run in windows service, it's don't work together like I need.

First I start communication with OPC DA server and second I want start TCP Listerner

 public void Start()
    {
        try
        {
            T1 = new Thread(new ThreadStart(DoOpc));
            T1.Start();

            T2 = new Thread(new ThreadStart(TcpConn));
            T2.Start();

        }
        catch (Exception e)
        {
            Program.LogEntry("Error", e.ToString(), "Fatal");
        }
    }

Methods:

public static void TcpConn()
    {
        try
        {
            Program.LogEntry("TCP Comm", "Theard start...");

            Int32 port = Int32.Parse(ConfigurationManager.AppSettings["TCP_port"]);
            IPAddress localAddr = IPAddress.Parse(ConfigurationManager.AppSettings["TCP_IP"]);
            TcpServer = new TcpListener(localAddr, port);
            TcpServer.Start();

            const int bytesize = 2048 * 2048; // Constant, not going to change later  
            Byte[] bytes = new Byte[bytesize];

            String data = null;

            while (true)
            {
                TcpClient client = TcpServer.AcceptTcpClient();
                IPAddress TcpIPClient = ((IPEndPoint)(client.Client.RemoteEndPoint)).Address;

                NetworkStream stream = client.GetStream();
                data = null;
                Program.LogEntry("TCP Comm", "Connected! IP: " + TcpIPClient);

                int i;

                if (StopTcp == true)
                {
                    Program.LogEntry("Service status", "Stoping TCP server...");

                    client.Close();
                    client.GetStream().Close();

                    TcpServer.Stop();

                    break;
                }


                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                    Program.LogEntry("TCP Comm", "Received: " + data);
                    string output = ProccessData(data);

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(output);

                    Program.LogEntry("TCP Comm", "Output: " + output);
                    stream.Write(msg, 0, msg.Length);
                }
                stream.Close();
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e.ToString());
            Program.LogEntry("TCP Comm", "SocketException: " + e.ToString(), "Fatal");

        }
        finally
        {
            Console.WriteLine("TCP: bye bye");
            Program.LogEntry("TCP Comm", "Bye Bye", "Warning");
            TcpServer.Stop();
            System.Environment.Exit(6);
        }
    }

OPC

 private static void DoOpc()
    {
        try
        {
            URL url = new URL(ConfigurationManager.AppSettings["OPC_Server"]);
            OpcServer = new Opc.Da.Server(new OpcCom.Factory(), url);
            OpcServer.Connect();

            if (OpcServer.IsConnected == true)
            {
                Program.LogEntry("OPC Client", "Connected !");
            }
            else
            {
                Program.LogEntry("OPC Client", "NOT Connected!", "Fatal");
            }

            OpcServer.ServerShutdown += new Opc.ServerShutdownEventHandler(OnServerShutdown);

            // Evidencia groupy/channelu ------Create group
            Opc.Da.SubscriptionState state = new Opc.Da.SubscriptionState();
            state.ClientHandle = 0;
            //state.Name = "Device1";
            state.UpdateRate = 500;
            state.Active = true; // true;
            Opc.Da.Subscription group = (Opc.Da.Subscription)OpcServer.CreateSubscription(state);

            // Callback on Data change
            group.DataChanged += new Opc.Da.DataChangedEventHandler(OnDataChange);

            Opc.Da.Item NewItem;
            List<Opc.Da.Item> NewItems = new List<Opc.Da.Item>();
            foreach (var item in ActiveItems.Where(x => x.Active == true))
            {
                NewItem = new Opc.Da.Item();
                NewItem.ClientHandle = 0;
                NewItem.ItemName = item.Device + "." + item.Tag; //int4 = 32 bit
                NewItems.Add(NewItem);
            }

            Item[] Items = NewItems.ToArray();
            ItemResult[] ir = group.AddItems(Items);

            SubscriptionState activatestate = group.GetState();
            activatestate.Active = true;
            group.ModifyState((int)Opc.Da.StateMask.Active, activatestate);
            TcpConn();

        }
        catch (Exception e)
        {
            Program.LogEntry("Error with OPC connection", e.ToString(), "Fatal");

        }

    }
0

There are 0 best solutions below