-1

I am developing windows forms application. I am communicating with serial port using separate thread. On button click I am closing the serial port and aborting the thread using Thread.Abort().But I am getting

Thread was being aborted exception.

private void button1_Click(object sender, EventArgs e)
{
   Thread1.Abort(); 
   if (isPortOpened)
   {                
      serialPort1.DataReceived -= DataReceivedHandler;
      serialPort1.Close();                
   }
}
croxy
  • 4,082
  • 9
  • 28
  • 46
sowjanya attaluri
  • 903
  • 2
  • 9
  • 27
  • 1
    Do the closing in a `finally` block – Alexander Derck Jan 28 '16 at 13:27
  • 6
    `Thread.Abort` is being explicitly called. What do you expect? You should [***never, ever, ever, ever*** call `Thread.Abort`](http://stackoverflow.com/questions/3632149/question-about-terminating-a-thread-cleanly-in-net). Really. You should signal to the thread to finish, and then call `Thread1.Join` to wait until it finishes gracefully. – spender Jan 28 '16 at 13:29
  • Try removing the following line: `Thread1.Abort();`. Once removed, never put back in. –  Jan 28 '16 at 13:36
  • DataReceived event is already called on separate background thread. What is the purpose of your separate thread exactly? – Arie Jan 28 '16 at 13:42
  • @spender: I tried your suggestion and is working fine. Using a flag, I send signal to the thread to finish indirectly.Thanks a lot. – sowjanya attaluri Jan 28 '16 at 13:53
  • @spender ... I would add ... never use `Thread` if you don't have to ... better use `Task`s – Random Dev Jan 28 '16 at 13:55
  • @sowjanyaattaluri : Great. Thread.Abort is evil! I wrapped my comment into an answer for you to accept. – spender Jan 28 '16 at 13:55
  • @Carsten AFAIK There are no Task based methods on SerialPort. It's a funny one. OP might be able to operate on SerialPort.BaseStream instead, but it would be a big deviation from current architecture. – spender Jan 28 '16 at 13:58
  • ... are there `Thread` based ones? but never mind – Random Dev Jan 28 '16 at 13:59

1 Answers1

4

Thread.Abort is being explicitly called. What do you expect?

You should never, ever, ever, ever call Thread.Abort. Really.

You should signal to the thread to finish, and then call Thread1.Join to wait until it finishes gracefully

Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351