473,387 Members | 1,903 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Thread not terminating with the application main form closure.

I'm new to C# and threading, so hopefully this is a simple newbie question.

I have a form that is supposed to listen for network traffic on a given port
and decode and display any interesting traffic it sees. To do this I've
launched a separate thread to do the listening.

When I run my form it seems to work fine, but when I close the form the
thread is not being terminated and Task Manager shows the application process
still executing. I tried adding code the the form closing event to abort the
thread, then join it to make sure it was closing properly, and the
application stopped on the join() call, reinforcing that the thread was not
terminating.

Please take pity on a newbie and tell me what I'm I'm doing wrong, or point
me to a good reference. The examples I've seen do no cleanup of the thread,
so I assumed it is supposed to be terminated with the parent application, but
that does not seem to be the case.

The interesting code is:

private void frmMain_Load(object sender, System.EventArgs e)
{
this._ServerIP = new IPEndPoint(IPAddress.Parse
App.Config.DestinationIPAddress), App.Config.DestinationPort);
this._Client = new UdpClient(new IPEndPoint(IPAddress.Any,
App.Config.ListenPort));
this._ListenThread = new Thread(new ThreadStart(RecieveBroadcast));
this._ListenThread.Start();
}

private void RecieveBroadcast()
{
IPEndPoint recieveIP = new IPEndPoint(IPAddress.Any, 0);

while(true)
{
byte[] data = _Client.Receive(ref recieveIP);
}
}
Oct 21 '05 #1
2 1783
I have seen this before. You have correctly identified the symptoms
and taken the first steps at solving the problem. But there is another
problem...

Socket.Receive() is a blocking call. Once a thread enters this call,
it will not get the opportunity to abort itself until the receive
completes. But what if the socket never receives any more data?
Yah... exacly what you are seeing; your program hangs.

You should probably alter the algorithm that you are using in this
thread to only call Socket.Receive if Socket.Available is greater than
0; This way when you want to abort the thread it will respond.

To demonstrate the difference in behavior, here is a little sample:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class klass
{
private static Thread t_client;
private static Socket s_client;
private static bool listen;

public static void Main(string[] args)
{
Console.WriteLine("Hello There");
if(args.Length > 0 && args[0] == "listen")
listen = true;
startClient();
Thread.Sleep(2000);
t_client.Abort();
t_client.Join();
}
private static void startClient()
{
s_client = ConnectSocket("www.microsoft.com", 80);
if(listen)
t_client = new Thread(new ThreadStart(listener));
else
t_client = new Thread(new ThreadStart(spinner));
t_client.Start();
}
private static void spinner()
{
while(true)
{
// chose a better time to call Receive only when there is data...
}
}
private static void listener()
{
while(true)
{
byte[] buffer = new byte[256];
int receiveCount = s_client.Receive(buffer);
Console.WriteLine("Received {0} bytes", receiveCount);
}
}
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntry(server);

// Loop through the AddressList to obtain the supported
AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not
compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream,
ProtocolType.Tcp);

tempSocket.Connect(ipe);

if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
}

Oct 21 '05 #2
I failed to mention that I'm trying to listen for UDP broadcasts and I can't
apparently use your otherwise lovely routine.

"Nick Hertl" wrote:
I have seen this before. You have correctly identified the symptoms
and taken the first steps at solving the problem. But there is another
problem...

Socket.Receive() is a blocking call. Once a thread enters this call,
it will not get the opportunity to abort itself until the receive
completes. But what if the socket never receives any more data?
Yah... exacly what you are seeing; your program hangs.

You should probably alter the algorithm that you are using in this
thread to only call Socket.Receive if Socket.Available is greater than
0; This way when you want to abort the thread it will respond.

To demonstrate the difference in behavior, here is a little sample:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class klass
{
private static Thread t_client;
private static Socket s_client;
private static bool listen;

public static void Main(string[] args)
{
Console.WriteLine("Hello There");
if(args.Length > 0 && args[0] == "listen")
listen = true;
startClient();
Thread.Sleep(2000);
t_client.Abort();
t_client.Join();
}
private static void startClient()
{
s_client = ConnectSocket("www.microsoft.com", 80);
if(listen)
t_client = new Thread(new ThreadStart(listener));
else
t_client = new Thread(new ThreadStart(spinner));
t_client.Start();
}
private static void spinner()
{
while(true)
{
// chose a better time to call Receive only when there is data...
}
}
private static void listener()
{
while(true)
{
byte[] buffer = new byte[256];
int receiveCount = s_client.Receive(buffer);
Console.WriteLine("Received {0} bytes", receiveCount);
}
}
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntry(server);

// Loop through the AddressList to obtain the supported
AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not
compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream,
ProtocolType.Tcp);

tempSocket.Connect(ipe);

if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
}

Oct 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Xarky | last post by:
Hi, I am creating a windows form, and when a specified event occurs (button click), I am hiding the windows form and opening a new windows form. When opening the new windows form and closing...
20
by: Doug Thews | last post by:
I ran into an interesting re-pain delay after calling the Abort() method on a thread, but it only happens the very first time I call it. Every time afterward, there is no delay. I've got a...
2
by: MuZZy | last post by:
HI, As i posted below i have an app with a separate thread listening for a tcp client connection. In the simplest way it looks like: void ListenerThreadFunction() { TcpListener l = new...
6
by: Tomaz Koritnik | last post by:
I have a class that runs one of it's method in another thread. I use Thread object to do this and inside ThreadMethod I have an infinite loop: While (true) { // do something Thread.Sleep(100);...
7
by: Edwin | last post by:
Hello, I would like the Main()-thread to end (because it runs out of the code), but all started threads should continue. Is this possible. Eg. static void Main(string args) {
9
by: Li Pang | last post by:
Hi I make an app which can run some sub processes through multiple threads. I'd like to know how to terminate all sub-threads when the main thread is closed thanks in advance
2
by: Byron | last post by:
I'm new to C# and threading, so hopefully this is a simple newbie question. I have a form that is supposed to listen for network traffic on a given port and decode and display any interesting...
3
by: Adam Honek | last post by:
How does one attach a thread so it can update the UI of a form? The other thing is I thought .IsBackground makes the thread active so it doesn't stop looping until the main thread dies. This...
2
by: Mike | last post by:
Hello, Ok I have 2 classes in my project, one is the main form and one is a connection class, at a certain event on my main form a new instance is made of the connection class, and a reference...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.