Click here to Skip to main content
15,891,316 members
Home / Discussions / C#
   

C#

 
AnswerRe: USB OVER NETWORK Pin
joost.versteegen8-Jul-18 20:58
joost.versteegen8-Jul-18 20:58 
AnswerRe: USB OVER NETWORK Pin
CP_Member88831-Jul-18 2:42
CP_Member88831-Jul-18 2:42 
QuestionWhat is the format of a SQLConnection connection string? Pin
Xarzu6-Jul-18 10:19
Xarzu6-Jul-18 10:19 
AnswerRe: What is the format of a SQLConnection connection string? Pin
Richard Deeming6-Jul-18 11:38
mveRichard Deeming6-Jul-18 11:38 
QuestionRtf Table Creating and Printing Pin
Member 117104825-Jul-18 20:49
Member 117104825-Jul-18 20:49 
AnswerRe: Rtf Table Creating and Printing Pin
Richard MacCutchan5-Jul-18 22:00
mveRichard MacCutchan5-Jul-18 22:00 
AnswerRe: Rtf Table Creating and Printing Pin
Eric Goedhart5-Jul-18 23:31
professionalEric Goedhart5-Jul-18 23:31 
QuestionMultiThreading help Pin
solutionsville5-Jul-18 6:05
solutionsville5-Jul-18 6:05 
Hi, I inherited a program from a programmer that has since left the company. He built it with threading and the program crashes I think due to starting more threads than the system can handle. I am thinking that I need to implement a Thread Pool for this code, and am unsure how I should do that not having done it before, and complicating the matter of modifying the existing code.

So, here is the existing code that uses the threading;

C#
using my.data;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;

namespace CnaFirmware
{

    public class DbUpdateFromField
    {
        Dictionary<string, CNA> cnas;
        ConcurrentQueue<string> ConsoleQueue;
        EventWaitHandle UpdateComplete;
        ClsUdpDispatcher UdpDispatcher;
        List<string> updates;

        // this class starts a thread that downloads config data from all cnas, then updates the cna_firmware table.
        class CNA
        {
            public string ip;
            public string firmware;
            public int cktid;
            public bool updated;
            public bool error;

            public CNA(string i, string f, int c)
            {
                this.ip = i;
                this.firmware = f;
                this.cktid = c;
                this.updated = false;
                this.error = false;
            }
        }

        public DbUpdateFromField(ClsUdpDispatcher disp, ConcurrentQueue<string> q, EventWaitHandle op_done)
        {
            UdpDispatcher = disp;
            ConsoleQueue = q;
            UpdateComplete = op_done;
            Log("start");
            updates = new List<string>();
            cnas = new Dictionary<string, CNA>();
            new Thread(() => Start()).Start();
        }

        void Start()
        {
            GetIpList();
            GetCnaData();
        }
        void Log(string s)
        {
            ConsoleQueue.Enqueue("DbUpdate: " + s);
        }

        void GetCnaData()
        {
            SqlConnection DB;
            foreach (var v in cnas)
            {
                // get data from each cna, in sequence (not concurrent)
                new Thread(() => GetCnaInfo(v.Value)).Start();
            }
            // loop through all the cnas until either error or complete flag is set
            bool done;
            do
            {
                Thread.Sleep(50);
                done = true;
                foreach (var v in cnas)
                {
                    if (!v.Value.updated && !v.Value.error) done = false;
                }
            } while (!done);

            // all field cnas have responded or timed out. now update the DB
            if (updates.Count > 0)
            {
                Log(string.Format("Sending {0} updates to database...", updates.Count));

                using (DB = new SqlConnection(Globals.ConnectionString))
                {
                    try
                    {
                        DB.Open();
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message);
                        return;
                    }

                    try
                    {
                        using (SqlCommand sql = new SqlCommand())
                        {
                            sql.Connection = DB;
                            foreach (string query in updates)
                            {
                                sql.CommandText = query;
                                sql.ExecuteNonQuery();

                                // not sure if this is necessary
                                Thread.Sleep(10);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message);
                        return;
                    }
                }
            }
            else
            {
                Log("No updates");
            }

            Log("Operation complete");
            UpdateComplete.Set();
        }
        /*
 typedef struct
{
0            unsigned char  version;     // 1 or 2
1            unsigned char firmware[3];  // v2 only
2            unsigned char flags;        // v2 only
3            unsigned short not_used;    //
4            unsigned short label;
5            unsigned short len;      //<-- This is the length of the payload data (config data in our example).
}CCI_HDR_T;

 * header is followed by configuration data: all structs are the same first four bytes
 * 
 * typedef struct
    {
6                unsigned short cnaID;         // HEX <-- Hard coded to 0x1003
7                unsigned short version;       // HEX
    }
 * 
 * 00 11 11 11 22 33 33 44 44 55 55 66 66 77 77
 */
        void SendGetConfig(string ip, ConcurrentQueue<UdpMessage> C)
        {
            byte[] msg = new byte[11];
            msg[0] = 1;
            msg[7] = 5;
            msg[8] = 0x42; // rx = 0x43
            UdpDispatcher.Send(new UdpMessage(ip, 20367, msg, 11), C);
        }
        void GetCnaInfo(CNA cna)
        {
            int WaitTicks;
            ConcurrentQueue<UdpMessage> CnaRxQ = new ConcurrentQueue<UdpMessage>();
            int tries = 0;
            while (++tries < 4)
            {
                WaitTicks = 0;
                //if (tries > 1) ConsoleQueue.Enqueue(string.Format("{0}: retry get-config",IpAddress));
                SendGetConfig(cna.ip, CnaRxQ);
                while (++WaitTicks < 100) // 10 seconds
                {
                    if (CnaRxQ.TryDequeue(out UdpMessage msg))
                    {
                        ushort label = (ushort)((msg.data[7] << 8) + (ushort)msg.data[8]);
                        if (label == 0x0543)
                        {
                            // this is a CONFIG_REPLY:
                            if (msg.data[0] > 1)
                            {
                                string firmware = string.Format("{0}.{1}.{2}", msg.data[1], msg.data[2], msg.data[3]);
                                //ushort platform = (ushort)((msg.data[11] << 8) + (ushort)msg.data[12]);  // HEX!
                                //ushort version = (ushort)((msg.data[13] << 8) + (ushort)msg.data[14]);
                                //Platform = string.Format("{0:X4}.{1}", platform, version);
                                cna.updated = true;
                                // don't update db unless they are different:
                                if (cna.firmware == firmware)
                                {
                                    Log(string.Format("Skipping {0}: firmware is current", cna.ip));
                                }
                                else
                                {
                                    Log("Updating " + cna.ip);
                                    QueryBuilder qb = new QueryBuilder("update cna_firmware set firmware_rev = ");
                                    qb.AddString(firmware, QBOptions.NONE);
                                    qb.Query += " where ip_address = ";
                                    qb.AddString(cna.ip, QBOptions.NONE);
                                    updates.Add(qb.Query);
                                }
                                return;
                            }
                            else
                            {
                                // got unexpected data
                                Log(string.Format("Skipping {0}: unexpected data received", cna.ip));
                                return;
                            }
                        }
                        else
                        {
                            // got unexpected data
                            Log(string.Format("Skipping {0}: unexpected data received", cna.ip));
                            return;
                        }
                    }
                    Thread.Sleep(100);
                }
            }
            Log("Unable to fetch config data from " + cna.ip);
            cna.error = true;
        }

        void GetIpList()
        {
            SqlConnection DB;
            string query;
            using (DB = new SqlConnection(Globals.ConnectionString))
            {
                try
                {
                    DB.Open();
                }
                catch (Exception)
                {
                    UpdateComplete.Set();
                    return;
                }
                query = "select ip_address, n_cktid, firmware_rev from cna_firmware order by ip_address";
                try
                {
                    using (SqlCommand sql = new SqlCommand(query, DB))
                    {
                        using (SqlDataReader dr = sql.ExecuteReader())
                        {
                            if (dr.HasRows)
                            {
                                while (dr.Read())
                                {
                                    int ckt = Sql.Read<int>(dr, "n_cktid");
                                    string ip = Sql.Read<string>(dr, "ip_address");
                                    string fw = Sql.Read<string>(dr, "firmware_rev");
                                    if (cnas.ContainsKey(ip)) continue;
                                    cnas.Add(ip, new CNA(ip, fw, ckt));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log(ex.Message);
                }
            }
        }
    }
}


Thanks,
AnswerRe: MultiThreading help Pin
Dave Kreskowiak5-Jul-18 6:29
mveDave Kreskowiak5-Jul-18 6:29 
GeneralRe: MultiThreading help Pin
solutionsville6-Jul-18 4:28
solutionsville6-Jul-18 4:28 
GeneralRe: MultiThreading help Pin
Dave Kreskowiak6-Jul-18 4:51
mveDave Kreskowiak6-Jul-18 4:51 
AnswerRe: MultiThreading help Pin
solutionsville10-Jul-18 2:59
solutionsville10-Jul-18 2:59 
AnswerRe: MultiThreading help Pin
OriginalGriff5-Jul-18 19:45
mveOriginalGriff5-Jul-18 19:45 
QuestionHow To solve Unity.Instance.Resolve(new ResolverOverride[] Pin
Member 110561804-Jul-18 4:56
Member 110561804-Jul-18 4:56 
AnswerRe: How To solve Unity.Instance.Resolve(new ResolverOverride[] Pin
Richard Deeming4-Jul-18 7:32
mveRichard Deeming4-Jul-18 7:32 
QuestionFilter records between two dates( using two datepicker) from text file in c# Pin
Mohamed Fahad M4-Jul-18 2:20
Mohamed Fahad M4-Jul-18 2:20 
AnswerRe: Filter records between two dates( using two datepicker) from text file in c# Pin
Pete O'Hanlon4-Jul-18 2:32
mvePete O'Hanlon4-Jul-18 2:32 
QuestionMaskedTextBox Focus ? Pin
ibrahimayhans3-Jul-18 1:42
ibrahimayhans3-Jul-18 1:42 
AnswerRe: MaskedTextBox Focus ? Pin
OriginalGriff3-Jul-18 2:19
mveOriginalGriff3-Jul-18 2:19 
GeneralRe: MaskedTextBox Focus ? Pin
ibrahimayhans3-Jul-18 2:33
ibrahimayhans3-Jul-18 2:33 
AnswerRe: MaskedTextBox Focus ? Pin
Eddy Vluggen3-Jul-18 2:31
professionalEddy Vluggen3-Jul-18 2:31 
GeneralRe: MaskedTextBox Focus ? Pin
ibrahimayhans3-Jul-18 2:34
ibrahimayhans3-Jul-18 2:34 
GeneralRe: MaskedTextBox Focus ? Pin
Eddy Vluggen3-Jul-18 2:37
professionalEddy Vluggen3-Jul-18 2:37 
AnswerRe: MaskedTextBox Focus ? Pin
Alan N3-Jul-18 3:29
Alan N3-Jul-18 3:29 
QuestionFollowing Jose Menendez Póo Calendar project Pin
Member 128234452-Jul-18 18:44
Member 128234452-Jul-18 18:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.