'BackgroundWorker.IsBusy staying true at all times during serial port operations?

I am working on a Data Acquisition and Logging project which has two windows (forms). On the main window, there is a trigger button which opens another form (second form) showing the message "Please wait while the channels' data is being acquired" and acquires data serially by sending a token through the COM port and then saves the acquired data of 13 DAQ cards to a sql database. The second form does all the work in a background thread so that the clock timer on the main form also keeps on ticking (time stamps needed for charting).

enter image description here

The problem is that on triggering the serial port, the RunWorkerAsync() method of the BackgroundWorker class stays busy i.e BackgroundWorker.IsBusy = true at all times and hence the serial port cannot perform the required write and read operations. My question is can serial operations be performed like this in the background thread? Or do I look for other options?

The relevant code chunk of the Main Form is:

//////////////Triggering, DAQ and DB Logging/////////////////////////

    private void Button_Trigger_Click(object sender, EventArgs e)
    {
                            
        this.Cursor = Cursors.WaitCursor;

        
        c_DateTime = DateTime.Now.ToString();

        button_Trigger.Enabled = false;

        Form form4 = new WAIT_FORM();
        form4.ShowDialog();

        MessageBox.Show("data acquisition and logging finished");

        

        this.Cursor = Cursors.Default;
   }

Form4 code: (There are 13 DAQ Cards polled one by one)

 BackgroundWorker serialRtx = new BackgroundWorker();

 serialRtx.DoWork += serialRtx_DoWork;

 SerialPort serialP = new SerialPort("COM1", 57600);  

 private void Timer_Wait_Tick(object sender, EventArgs e)
    {
        

        if (cardNo == 13)
        {
            cardNo = 1;
            serialP.Close();
            Close();

        }



        if (!serialRtx.IsBusy) // serialRtx.IsBusy = true all times
            serialRtx.RunWorkerAsync();

 private void serialRtx_DoWork(object sender, DoWorkEventArgs e)
    {
        byte[] send_Packet = { 170, 170, 170, (byte)cardNo };

        while (cardNo < 13)
         {

        try
        {
            send_Packet[3] = (byte)cardNo;
            for (int i = 0; i < 4; i++)
            {
                serialP.Write(send_Packet, i, 1);
                Console.WriteLine(send_Packet[i]);
                Thread.Sleep(1);
            }


        }

        catch (Exception caught)
        {
            string str = caught.Message;
            MessageBox.Show(str);
        }

        cardNo++;

        //if (cardNo == 13)
        //{
        //    cardNo = 1;

        //}            
        
    }

    }

Code Update:

 public WAIT_FORM()
    {
        InitializeComponent();

        serialP.DataBits = 8;
        serialP.StopBits = StopBits.One;
        //serialP.Handshake = Handshake.RequestToSend;
        serialP.Parity = Parity.None;
        
        serialP.DataReceived += serialP_DataReceived;

        ////serialP.WriteTimeout = 3000; 
        ////serialP.ReadTimeout = 3000;
        
        serialP.Open();            
       
        serialRtx.DoWork += serialRtx_DoWork;            

        if (!serialRtx.IsBusy)
            serialRtx.RunWorkerAsync();

        serialRtx.RunWorkerCompleted += serialRtx_RunWorkerCompleted;
        
    }
private void serialRtx_DoWork(object sender, DoWorkEventArgs e)
        {          
            byte[] send_Packet = { 0xAA, 0xAA, 0xAA, 2 };
                try
                {
                    Console.Write("Card no=");
                    Console.WriteLine(cardNo);
                    
                    for (int i = 0; i < 4; i++)
                    {
                        serialP.Write(send_Packet, i, 1);
                        Console.Write("ds=");
                        Console.WriteLine(send_Packet[i]);
                        Thread.Sleep(1);
                    }

                }

                catch (Exception caught)
                {
                    string str = caught.Message;
                    MessageBox.Show(str);
                }
        }
        
private void serialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            while (serialP.BytesToRead > 0)
            {                
                dataBit1 = serialP.ReadByte();
                Console.Write("dr1=");
                Console.WriteLine(dataBit1);

                dataBit2 = serialP.ReadByte();
                Console.Write("dr2=");
                Console.WriteLine(dataBit2);                
                               
                try
                {               
                    logData[sample_No, chNo - 1] = ((dataBit1 * 256) + dataBit2); // data[bitCount];//two byes per one DAQ channel
                    logData[sample_No, chNo - 1] = (logData[sample_No, chNo - 1] * 10 / 32768) - 10;//engineered value
                    Console.Write("sample_No=");
                    Console.WriteLine(sample_No);
                    Console.Write("chNo=");
                    Console.WriteLine(chNo);
                    Console.Write("logdata=");
                    Console.WriteLine(logData[sample_No, chNo - 1]);

                    chNo++;

                    if (chNo > 8)
                    {
                        sample_No++;
                        chNo = 1;
                    }

                    if (sample_No > 3999)//total 4000 samples of 8 channels
                    {
                        cardNo++;
                        sample_No = 0;
                    }
                   

                    
                }
                catch (IndexOutOfRangeException)
                { }                
            }
        }
private void serialRtx_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Close();
        }
        
        private void WAIT_FORM_FormClosing(object sender, FormClosingEventArgs e)
        {
            serialP.Close();
        }         

 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source