2

I have created a WPF application.There are two threads running in my application:

  1. First thread listen asynchronously for TCP packets on PORT 40010 and push data to MSMQ
  2. Second thread pop data from MSMQ

When I close the application by clicking on window close button it shows no error. But when I start the application again it throws the exception:

Unable to start Listrner : Only one usage of each socket address 
    (protocol/network address/port) is normally permitted

When I restart my PC it run first time successfully but on closing the application it does not work again

DocMax
  • 12,094
  • 7
  • 44
  • 44
Suri
  • 518
  • 2
  • 6
  • 20

1 Answers1

6

You shall not kill your threads.

What you should do is to provide a nice way for them to finish. On close of your application you should set some variable:

volatile bool shouldClose;

and use that variable inside your threads say before poping next package and brake your infinite loop there.

As for main application it should wait for your threads to finish.

for volatile keyword see documentation.

Rafal
  • 12,391
  • 32
  • 54
  • 1
    +, to sum that up: it's the cancellation-token-pattern, eg introduced for `System.Threading.Task.Task` in .Net 4.0 (http://www.dotnetcurry.com/ShowArticle.aspx?ID=493, http://stackoverflow.com/questions/3712939/cancellation-token-in-task-constructor-why) - So if you work with .Net 4.0 and use tasks, you can simply go for that routine (and should)! –  Jan 10 '13 at 07:38