连续读取Tcpclient的背景工作者的数组

时间:2016-12-20 06:39:10

标签: c# backgroundworker tcpclient

我们在C#中开发了Window服务,在后台worker的帮助下使用TcpClient读取数据。在这里,我们正在从多个IP中读取数据,因此使用后台工作程序数组来实现此目的。我们的服务工作得非常好,但几个小时后,其中一个线程停止运行。对于这里,我正在粘贴与此问题相关的功能。 调用序列 1. StartMonitoring 2. Dowork

假设有两行来自数据库,因此创建了两个后台工作者对象,这些对象将调用backgroundWorkerFiles_DoWork函数。 在backgroundWorkerFiles_DoWork函数中,int i =(int)e .Argument;首先是0然后是1,根据0和1,它们将IP连接到其端口。但是经过一段时间我总是来1而不是0.最初两次运行但是一个线程停止运行并且总是给1连接IP而不是0。 请帮助我们摆脱这个问题。我也在努力。如果你愿意,我也可以粘贴完整的代码。

public static string SERVICE_TIMER =Convert.ToString(ConfigurationSettings.AppSettings["SERVICE_TIMER"]);
    public static int READING_TIMER = Convert.ToInt32(ConfigurationSettings.AppSettings["READING_TIMER"]);
    public static string PLANT = Convert.ToString(ConfigurationSettings.AppSettings["PLANT"]);
    public static string FAMILY = Convert.ToString(ConfigurationSettings.AppSettings["FAMILY"]);
    public static BackgroundWorker[] BackgroundWorker_Controllers = new BackgroundWorker[maxThreads];
    public static TcpClient[] tcpClientRead = new TcpClient[maxThreads];
    public static TcpClient[] tcpClientWrite = new TcpClient[maxThreads];
    public CONTROLLERS[] listObj = new CONTROLLERS[maxThreads];
    public Thread _thread;


private void startMonitoring()    
    {    
        //while (true)
        //{`enter code here`
        try
        {
        CHECK:
            WriteLog("startsMonitoring");
            Thread.Sleep(1000 * 20);
            if (ReadSetting())
            {
                Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\\Control Panel\\International", "sShortDate", "dd-MMM-yyyy");
                CreateTables();
                query = "select * from XXES_CONTROLLERS where active='Y'";
                DataTable dt = returnDataTable(query);
                if (dt.Rows.Count > 0)
                {
                    maxThreads = dt.Rows.Count;
                    if (maxThreads > 0)
                    {
                        BackgroundWorker_Controllers = new BackgroundWorker[maxThreads];
                        tcpClientRead = new TcpClient[maxThreads];
                        tcpClientWrite = new TcpClient[maxThreads];
                        listObj = new CONTROLLERS[maxThreads];
                        int Counter = 0;
                        foreach (DataRow dr in dt.Rows)
                        {
                            listObj[Counter] = new CONTROLLERS();
                            listObj[Counter].DID = Convert.ToString(dr["DID"]).Trim();
                            listObj[Counter].IP_ADDR = Convert.ToString(dr["IP_ADDR"]).Trim();
                            listObj[Counter].PORT = Convert.ToString(dr["PORT"]).Trim();
                            listObj[Counter].STAGE = Convert.ToString(dr["STAGE"]).Trim();
                            listObj[Counter].INPUT_MODE = Convert.ToString(dr["INPUT_MODE"]).Trim();
                            listObj[Counter].READING_TYPE = Convert.ToString(dr["READING_TYPE"]).Trim();
                            Counter++;
                        }
                        for (int f = 0; f < maxThreads; f++)
                        {
                            BackgroundWorker_Controllers[f] = new BackgroundWorker();
                            BackgroundWorker_Controllers[f].DoWork += new DoWorkEventHandler(backgroundWorkerFiles_DoWork);
                            BackgroundWorker_Controllers[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerFiles_RunWorkerCompleted);
                            //BackgroundWorker_Controllers[f].ProgressChanged +=
                            //    new ProgressChangedEventHandler(backgroundWorkerFiles_ProgressChanged);
                            //BackgroundWorker_Controllers[f].WorkerReportsProgress = true;
                            BackgroundWorker_Controllers[f].WorkerSupportsCancellation = false;
                        }

                        for (int threadNum = 0; threadNum < maxThreads; threadNum++)
                        {
                            if (!BackgroundWorker_Controllers[threadNum].IsBusy)
                            {
                                BackgroundWorker_Controllers[threadNum].RunWorkerAsync(threadNum);
                            }
                        }
                    }

                }

            }
            else
            {
                goto CHECK;
            }
        }
        catch (Exception ex)
        {
            ErrorLog("Module:startMonitoring: " + ex.Message.ToString());
        }
        finally { }
        // }
    }

private void backgroundWorkerFiles_DoWork(object sender, DoWorkEventArgs e)
    {

        string ip = ""; bool toggle = false; DateTime todaysdate = new DateTime();

        try
        {
            BackgroundWorker sendingWorker = (BackgroundWorker)sender;//Capture the BackgroundWorker that fired the event
             int i = (int)e.Argument;
            #region Main
            while (!sendingWorker.CancellationPending)
            {
                #region MainTry
                try
                {
                    try
                    {
                        StreamWriter sw = new StreamWriter(AppPath + "\\Live.txt");
                        sw.WriteLine(DateTime.Now);
                        sw.Close();
                    }
                    catch { }
                    finally { }
                    #region WhileLOOP
                    todaysdate = GetServerDateTime();
                    if (listObj[i].toggle == false)
                    {
                        try
                        { if (tcpClientRead[i].Connected) tcpClientRead[i].Close(); }
                        catch { }
                        finally { }
                        tcpClientRead[i] = new System.Net.Sockets.TcpClient();
                        tcpClientRead[i].Connect(listObj[i].IP_ADDR, Convert.ToInt32(listObj[i].PORT));
                    }
                    //if (tcpClientRead[i].Connected)
                    if (isPinging(listObj[i].IP_ADDR) && tcpClientRead[i].Connected)
                    {
                        query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and data_type='ERROR'";
                        EXEC_QUERY(query);
                        listObj[i].toggle = true;
                        //NetworkStream myNetworkStream = tcpClientRead[i].GetStream();
                        listObj[i].myNetworkStream = tcpClientRead[i].GetStream();
                        if (listObj[i].myNetworkStream.CanRead)
                        {
                            byte[] myReadBuffer = new byte[1024];
                            //  StringBuilder myCompleteMessage = new StringBuilder();
                            listObj[i].myCompleteMessage = new StringBuilder();
                            int numberOfBytesRead = 0;
                            //  Incoming message may be larger than the buffer size. 
                            while (listObj[i].myNetworkStream.DataAvailable)
                            {
                                listObj[i].myNetworkStream.Flush();
                                numberOfBytesRead = listObj[i].myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
                                listObj[i].myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
                                Thread.Sleep(READING_TIMER);
                            }
                            if (!string.IsNullOrEmpty(Convert.ToString(listObj[i].myCompleteMessage)))
                            {
                                query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and data_type='MSG'";
                                EXEC_QUERY(query);
                                //query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,SRLNO,STAGE,SCAN_DATE,DATA_TYPE) values('" + PLANT + "','" + FAMILY + "','" + Convert.ToString(listObj[i].myCompleteMessage) + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG')";
                                //EXEC_QUERY(query);
                                if (listObj[i].STAGE == "BP")
                                {
                                    WriteLog("Before Paint : " + Convert.ToString(listObj[i].myCompleteMessage));
                                    if (string.IsNullOrEmpty(BP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Length == 4)
                                        BP_HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
                                    if (string.IsNullOrEmpty(BP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Length != 4)
                                        BP_JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();

                                }
                                if (listObj[i].STAGE == "AP")
                                {
                                    WriteLog("After Paint : " + Convert.ToString(listObj[i].myCompleteMessage).Trim());
                                    if (string.IsNullOrEmpty(AP_HOOK) && Convert.ToString(listObj[i].myCompleteMessage).Trim().Length == 4)
                                        AP_HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
                                    if (string.IsNullOrEmpty(AP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Trim().Length != 4)
                                        AP_JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
                                }
                                if (Convert.ToString(listObj[i].myCompleteMessage).Trim().Length == 4)
                                    listObj[i].HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
                                else if (Convert.ToString(listObj[i].myCompleteMessage).Trim().Length > 4)
                                    listObj[i].JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
                                if (!string.IsNullOrEmpty(listObj[i].HOOK) && !string.IsNullOrEmpty(listObj[i].JOB) && listObj[i].STAGE.Trim() == "BP")
                                {
                                    bool isCheck = false;
                                    Data = "";
                                    Data = get_Col_Value("select fcode_id || '#' || ITEM_CODE || '#' || final_label_date from XXES_JOB_STATUS where jobid='" + listObj[i].JOB.Trim() + "'"); // and final_label_date is null");
                                    if (Data.Contains('#'))
                                    {
                                        listObj[i].fcode_id = Convert.ToString(Data.Split('#')[0]).Trim();
                                        listObj[i].ITEM_CODE = Convert.ToString(Data.Split('#')[1]).Trim();
                                        listObj[i].FINAL_DATE = Convert.ToString(Data.Split('#')[2]).Trim();
                                    }
                                    else
                                    {
                                      listObj[i].FINAL_DATE=listObj[i].fcode_id = listObj[i].ITEM_CODE = "";
                                    }
                                    if (string.IsNullOrEmpty(listObj[i].fcode_id))
                                    {
                                        query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB :" + listObj[i].JOB + " is not buckleup','" + listObj[i].JOB + "')";
                                        EXEC_QUERY(query);
                                        WriteLog("JOB :" + listObj[i].JOB + " is not buckleup");
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(listObj[i].FINAL_DATE))
                                        {
                                            query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "Final sticker already taken for JOB :" + listObj[i].JOB + "','" + listObj[i].JOB + "')";
                                            EXEC_QUERY(query);
                                            isCheck = true;
                                            WriteLog("Final sticker already taken for JOB :" + listObj[i].JOB + "");
                                        }
                                        else if (!string.IsNullOrEmpty(listObj[i].HOOK))
                                        {
                                            query = "select * from (select JOBID from XXES_CONTROLLERS_DATA where hook_no='" + listObj[i].HOOK.Trim() + "' order by ENTRY_DATE DESC) where rownum=1";
                                            string jobid = get_Col_Value(query).Trim();
                                            if (!string.IsNullOrEmpty(jobid))
                                            {
                                                if (CheckExits("select count(*) from XXES_JOB_STATUS where jobid='" + jobid + "' and plant_code='" + PLANT.Trim() + "' and family_code='" + FAMILY.Trim() + "' and final_label_date is null"))
                                                {
                                                    query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB " + jobid + " already in paint shop on  HOOK " + listObj[i].HOOK + "','" + listObj[i].JOB + "')";
                                                    if (EXEC_QUERY(query))
                                                    {
                                                        isCheck = true;
                                                        WriteLog("JOB " + jobid + " already working on HOOK " + listObj[i].HOOK + "");
                                                    }
                                                }
                                            }
                                        }
                                        if (isCheck == false)
                                        {
                                            query = "select count(*) from XXES_CONTROLLERS_DATA  where JOBID='" + listObj[i].JOB.Trim() + "' and stage='" + listObj[i].STAGE.Trim() + "' and plant_code='" + PLANT.Trim().ToUpper() + "' and FAMILY_CODE='" + FAMILY.Trim() + "'";// and flag is null";
                                            if (CheckExits(query))
                                            {
                                                query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB: " + listObj[i].JOB + " Already HOOKED UP','" + listObj[i].JOB + "')";
                                                if (EXEC_QUERY(query))
                                                {
                                                    WriteLog("JOB: " + listObj[i].JOB + " Already HOOKED UP");
                                                }
                                            }
                                            else
                                            {
                                                query = @"insert into XXES_CONTROLLERS_DATA(PLANT_CODE,FAMILY_CODE,JOBID,HOOK_NO,STAGE,ENTRY_DATE,FCODE_ID,ITEM_CODE)
                                                            values('" + PLANT.Trim().ToUpper() + "','" + FAMILY.Trim().ToUpper() + "','" + listObj[i].JOB.Trim() + "','" + listObj[i].HOOK.Trim() + "','" + listObj[i].STAGE + "',SYSDATE,'" + listObj[i].fcode_id.Trim() + "','" + listObj[i].ITEM_CODE.Trim() + "')";
                                                if (EXEC_QUERY(query))
                                                {
                                                    WriteLog("Inserted= " + query);
                                                    query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "LAST JOB: " + listObj[i].JOB + " HOOKED UP','" + listObj[i].JOB + "')";
                                                    if (EXEC_QUERY(query))
                                                    {
                                                        WriteLog("LAST JOB: " + listObj[i].JOB + " HOOKED UP");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    listObj[i].FINAL_DATE=listObj[i].ITEM_CODE= listObj[i].fcode_id=listObj[i].JOB = listObj[i].HOOK = "";
                                }
                                else if (!string.IsNullOrEmpty(listObj[i].HOOK) && listObj[i].STAGE.Trim() == "AP")
                                {
                                    string data = "";
                                    data = get_Col_Value("select jobid || '#' || fcode_id || '#' || ITEM_CODE from XXES_CONTROLLERS_DATA where HOOK_NO='" + listObj[i].HOOK.Trim() + "' and stage='BP' and plant_code='" + PLANT.Trim().ToUpper() + "' and FAMILY_CODE='" + FAMILY.Trim() + "' and flag is null");
                                    if (!string.IsNullOrEmpty(data) && data.Trim().Contains('#'))
                                    {
                                        listObj[i].JOB = data.Split('#')[0].Trim();
                                        listObj[i].fcode_id = data.Split('#')[1].Trim();
                                        listObj[i].ITEM_CODE = data.Split('#')[2].Trim();
                                        query = @"insert into XXES_CONTROLLERS_DATA(PLANT_CODE,FAMILY_CODE,JOBID,HOOK_NO,STAGE,ENTRY_DATE,FCODE_ID,ITEM_CODE)
                                                            values('" + PLANT.Trim().ToUpper() + "','" + FAMILY.Trim().ToUpper() + "','" + listObj[i].JOB.Trim() + "','" + listObj[i].HOOK.Trim() + "','" + listObj[i].STAGE + "',SYSDATE,'" + listObj[i].fcode_id.Trim() + "','" + listObj[i].ITEM_CODE.Trim() + "')";
                                        if (EXEC_QUERY(query))
                                        {
                                            query = "update XXES_CONTROLLERS_DATA set flag='Y' where HOOK_NO='" + listObj[i].HOOK.Trim() + "' and flag is null";
                                            if (EXEC_QUERY(query))
                                            {
                                                WriteLog("Hook :" + listObj[i].HOOK + " Out from After Paint");
                                                query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "LAST JOB: " + listObj[i].JOB + " HOOK DOWN','" + listObj[i].JOB + "')";
                                                if (EXEC_QUERY(query))
                                                {
                                                    WriteLog("LAST JOB: " + listObj[i].JOB + " HOOKED DOWN");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','HookNo " + listObj[i].HOOK + " not found at before paint stage or already scanned','" + listObj[i].HOOK + "')";
                                        EXEC_QUERY(query);
                                        WriteLog("HookNo " + listObj[i].HOOK + " not found at before paint stage or already scanned");
                                    }
                                    listObj[i].JOB = listObj[i].HOOK = "";
                                }
                                else if (!string.IsNullOrEmpty(listObj[i].JOB) && listObj[i].STAGE.Trim() == "AP")
                                {
                                    query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','Please scan valid Hook','" + listObj[i].JOB + "')";
                                    EXEC_QUERY(query);
                                    WriteLog("Please scan valid Hook");
                                    listObj[i].JOB = listObj[i].HOOK = "";
                                }
                            }

                        }
                    }
                    else
                    {
                        listObj[i].toggle = false;
                        throw new SocketException(10060);
                    }
                    Thread.Sleep(Convert.ToInt32(SERVICE_TIMER) * 1000);
                    #endregion WhileLOOP
                }
                catch (SocketException ex)
                {
                    #region ERROR
                    string error = "";
                    if (ex.ErrorCode.Equals(10060))
                    {
                        error = listObj[i].IP_ADDR + " not connected. Please check the network";
                    }
                    else
                    {
                        if (ex.Message.Length > 500)
                            error = ex.Message.Substring(0, 498);
                        else
                            error = ex.Message.ToString();
                    }
                    listObj[i].toggle = false;
                    query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and DATA_TYPE='ERROR'";
                    EXEC_QUERY(query);
                    query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'ERROR','" + error.Trim() + "')";
                    EXEC_QUERY(query);
                    ErrorLog("Module:While Connecting Controller: " + ex.Message.ToString());
                    if (tcpClientRead[i].Connected)
                        tcpClientRead[i].Close();
                    #endregion ERROR
                }
                catch (Exception ex)
                {
                    #region ERROR
                    string error = "";
                    if (ex.Message.Length > 500)
                        error = ex.Message.Substring(0, 498);
                    else
                        error = ex.Message.ToString();
                    error = listObj[i].STAGE + "=>" + error;
                    listObj[i].toggle = false;
                    query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and DATA_TYPE='ERROR'";
                    EXEC_QUERY(query);
                    query = @"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'ERROR','" + error.Trim() + "')";
                    EXEC_QUERY(query);
                    ErrorLog("Module:While Connecting Controller: " + ex.Message.ToString());
                    #endregion ERROR
                }
                finally
                {
                    // toggle = false;
                    //tcpClientRead[i].Close();
                }
                #endregion MainTry

                //}

                Thread.Sleep(Convert.ToInt32(SERVICE_TIMER) * 1000);
            }

            #endregion MAIN
        }
        catch (Exception ex)
        {
            ErrorLog("Module:DoWork: " + ex.Message.ToString());
        }
        finally { }
    }
    public static bool isPinging(string ip)
    {
        bool isPing = false;
        try
        {
            Ping myPing = new Ping();
            PingReply reply = myPing.Send(ip, 1000);
            if (reply != null)
            {
                if (reply.Status.ToString().ToUpper() == "SUCCESS")
                    isPing = true;
                else
                    isPing = false;
            }
            return isPing;
        }
        catch { return isPing; }
        finally { }
    }


    //}
    //private void backgroundWorkerFiles_ProgressChanged(object sender, ProgressChangedEventArgs e)
    //{
    //    // Use this method to report progress to GUI
    //}

    private void backgroundWorkerFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        try
        {
            WriteLog("Worker Completed");
            for (int i = 0; i < maxThreads; i++)//Start a for loop
            {
                if (tcpClientRead[i].Connected)
                    tcpClientRead[i].Close();
            }
        }
        catch { }
        finally { }
    }

1 个答案:

答案 0 :(得分:0)

我已将后台工作者转换为TASK库。现在问题解决了谢谢。改变了以下内容: -

public static Task [] BackgroundWorker_Controllers = new Task [maxThreads]; // declration

//调用

for (int f = 0; f < maxThreads; f++)
{
var ii = f;
BackgroundWorker_Controllers[f] = new Task(() =>
{ 
ConnectControllers(ii, dt.Rows.Count); }, TaskCreationOptions.None);
                            BackgroundWorker_Controllers[f].Start();
}