Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
am developing windows application. it reads data through serialport and places into excel sheet.
after completion that thread should be killed/stopped.
here is the code :for button click.
C#
private void Download_Click(object sender, EventArgs e)
       {
           textBox2.Text = fName;
           p = 2;
           fName = @"C:\STL\Download\Download_" + DateTime.Now.ToString("dd MMM yy HH mm").Trim() + ".xls ";
           progressBar2.Visible = true;

           serialPort1.WriteLine("$GET,"+textBox3.Text.ToString()+",0,#");

           Thread downloadThread = new Thread(new ThreadStart(threadDownload));
           downloadThread.Start();

       }


and thread method is:
C#
public  void threadDownload()
{
        try
        {
            Excel.Application xlApp = default(Excel.Application);
            Excel.Workbook xlWorkBook = default(Excel.Workbook);
            Excel.Worksheet xlWorkSheet = default(Excel.Worksheet);

            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells[1, 1] = "Machine ID";
            xlWorkSheet.Cells[1, 2] = "Customer ID";
            xlWorkSheet.Cells[1, 3] = "Name";
            xlWorkSheet.Cells[1, 4] = "Total Balance";
            xlWorkSheet.Cells[1, 5] = "Paid Amount";
            xlWorkSheet.Cells[1, 6] = "Last Paid Date";
            xlWorkSheet.Cells[1, 7] = "Due Amount";

            // String machineID = textBox3.Text.ToString();
            if (textBox3.InvokeRequired)
            {
                textBox3.Invoke(new MethodInvoker(delegate { machId = textBox3.Text; }));
            }
            s = null;
            // int drows = 0;

            xlWorkSheet.Cells[1, 1].Interior.ColorIndex = 39;
            xlWorkSheet.Cells[1, 2].Interior.ColorIndex = 39;
            xlWorkSheet.Cells[1, 3].Interior.ColorIndex = 39;
            xlWorkSheet.Cells[1, 4].Interior.ColorIndex = 39;
            xlWorkSheet.Cells[1, 5].Interior.ColorIndex = 39;
            xlWorkSheet.Cells[1, 6].Interior.ColorIndex = 39;
            xlWorkSheet.Cells[1, 7].Interior.ColorIndex = 39;

            while (true)
            {
                run.WaitOne();

                s = System.Text.ASCIIEncoding.ASCII.GetString(buffer);

                string[] lines = Regex.Split(s, "[$#,]");
                int resp = Convert.ToInt32(lines[2]);


                int totalrows = Convert.ToInt32(lines[4]);
                int m = 100 / totalrows;

                if (resp == 0 && p <= totalrows + 1)
                {
                    for (int q = 1; q <= 7; q++)
                    {
                        if (q == 1)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[1];
                        if (q == 2)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[5];
                        if (q == 3)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[6];
                        if (q == 4)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[7];
                        if (q == 5)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[8];
                        if (q == 6)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[9];
                        if (q == 7)
                            ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[p, q]).Value2 = lines[10];

                    }
                    progressBar2.Invoke((MethodInvoker)delegate
                    {
                        if (progressBar2.Value < 100)
                            progressBar2.Value += m;
                    });


                    downrows = p - 1;

                    serialPort1.WriteLine("$GET," + machId + "," + downrows + ",#");
                    p++;
                }
                else
                {
                    if (MessageBox.Show("Transaction has been stopped", "Notification", MessageBoxButtons.OK) == DialogResult.OK)
                    {

                        progressBar2.Invoke((MethodInvoker)delegate
                        {

                            progressBar2.Value = 0;
                        });


                        return;
                    }
                }


                if (lines[3].Equals(lines[4]))
                {
                    serialPort1.WriteLine("$GET," + machId + ",65535,#");
                    progressBar2.Invoke((MethodInvoker)delegate
                       {

                           progressBar2.Value = 100;
                       });
                    break;
                }
                else if (p > totalrows + 1)
                    break;

                // drows++;
            }

            xlWorkBook.SaveAs(fName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);


        }//try
        catch (Exception p)
        {
            MessageBox.Show(p.StackTrace);
        }

        finally
        {
            if (xlApp != null)
                releaseObject(xlApp);
            if (xlWorkBook != null)
                releaseObject(xlWorkBook);
            if (xlWorkSheet != null)
                releaseObject(xlWorkSheet);
        }
        if (System.IO.File.Exists(fName))
        {
            if (MessageBox.Show("Would you like to open the excel file?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(fName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error opening the excel file." + Environment.NewLine +
                      ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }




}
Posted
Comments
smithjdst 26-Dec-13 5:04am    
when the thread finishes you can call Thread.abort() method. Note that the abort method does not guarantee that the thread will be destroyed, it just makes an attempt to do so.

I might also suggest that the thread be made a background thread as well. This way if the abort method does not work it will be destroyed when your app is destroyed. Threads not set as background will not be destroyed when your app is.
Member 10263519 26-Dec-13 5:11am    
thanks for quick reply.
i searched google ,using abort is dagerous.keeping thread as background will terminate the tthread only when application is closed.But i want to teminate it when i complete reading from serialport.

1 solution

"searched google ,using abort is dagerous.keeping thread as background will terminate the tthread only when application is closed.But i want to teminate it when i complete reading from serialport."
Yes, it is.
So remove the
C#
while(true)
And replace it with a
C#
while(runThread)
Instead.
You preset runThread to true before you start the thread, and set it to false when you want the thread to close itself. You can then check it has closed before you restart it.

But smithjd is right: this should definitely be a Background thread - use the BackgroundWorker class - both to ensure that the thread is killed when you app ends, and to ensure that the UI continues to run smoothly.
 
Share this answer
 
Comments
Member 10263519 27-Dec-13 0:08am    
ok, but here run is an object of AutoResetEvent, and am using thread
downloadThread.
OriginalGriff 27-Dec-13 1:53am    
Sorry, but that makes no sense to me - it's probably a lack-of-caffeine problem on my part, but I'm working on that...
Could you try explaining that in more detail, remembering I can't see you screen?
Member 10263519 27-Dec-13 2:19am    
ok,my serialport_datareceived() is like this:
<pre lang="c#"> private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{


if (serialPort1.BytesToRead>0)
{
buffer = new byte[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, buffer.Length);
run.Set();
}
}</pre>

when i click button , from my application serialport writes data to device and creates a thread then executes downloadThread() method at run.waitone()it's wait for the event,when device returns data serialport_datareceived event will be fired after reading data at run.set() that thread will be invoked and executes remaining of downloadThread() method.

But here am getting error as:
NullReferenceException was caught: Object reference not set to an instance of an object.

in catch() of downloadThread() method


plz help
OriginalGriff 27-Dec-13 4:48am    
That try...catch covers a large pile of code - you need to use the debugger to find out exactly which line is giving the problem. Try putting a breakpoint in the catch, and looking at the Exception object - they normally contain a file, together with line and column number where the error occurred - which should help you pinpoint the line. Then put a breakpoint on that line and run it again. When the BP triggers, look at each element within the line to find out which is null - then you can start looking at why it is null. But until you know which variable in which line, we are all guessing!
Member 10263519 30-Dec-13 0:50am    
ok thanq .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900