473,612 Members | 2,331 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(ob ject sender, System.EventArg s e)
{
this._ServerIP = new IPEndPoint(IPAd dress.Parse
App.Config.Dest inationIPAddres s), App.Config.Dest inationPort);
this._Client = new UdpClient(new IPEndPoint(IPAd dress.Any,
App.Config.List enPort));
this._ListenThr ead = new Thread(new ThreadStart(Rec ieveBroadcast)) ;
this._ListenThr ead.Start();
}

private void RecieveBroadcas t()
{
IPEndPoint recieveIP = new IPEndPoint(IPAd dress.Any, 0);

while(true)
{
byte[] data = _Client.Receive (ref recieveIP);
}
}
Oct 21 '05 #1
2 1812
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.Availabl e 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.Sock ets;
using System.Threadin g;

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

public static void Main(string[] args)
{
Console.WriteLi ne("Hello There");
if(args.Length > 0 && args[0] == "listen")
listen = true;
startClient();
Thread.Sleep(20 00);
t_client.Abort( );
t_client.Join() ;
}
private static void startClient()
{
s_client = ConnectSocket(" www.microsoft.c om", 80);
if(listen)
t_client = new Thread(new ThreadStart(lis tener));
else
t_client = new Thread(new ThreadStart(spi nner));
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.Receiv e(buffer);
Console.WriteLi ne("Received {0} bytes", receiveCount);
}
}
private static Socket ConnectSocket(s tring server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntr y(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(IPAddre ss address in hostEntry.Addre ssList)
{
IPEndPoint ipe = new IPEndPoint(addr ess, port);
Socket tempSocket =
new Socket(ipe.Addr essFamily, SocketType.Stre am,
ProtocolType.Tc p);

tempSocket.Conn ect(ipe);

if(tempSocket.C onnected)
{
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.Availabl e 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.Sock ets;
using System.Threadin g;

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

public static void Main(string[] args)
{
Console.WriteLi ne("Hello There");
if(args.Length > 0 && args[0] == "listen")
listen = true;
startClient();
Thread.Sleep(20 00);
t_client.Abort( );
t_client.Join() ;
}
private static void startClient()
{
s_client = ConnectSocket(" www.microsoft.c om", 80);
if(listen)
t_client = new Thread(new ThreadStart(lis tener));
else
t_client = new Thread(new ThreadStart(spi nner));
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.Receiv e(buffer);
Console.WriteLi ne("Received {0} bytes", receiveCount);
}
}
private static Socket ConnectSocket(s tring server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntr y(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(IPAddre ss address in hostEntry.Addre ssList)
{
IPEndPoint ipe = new IPEndPoint(addr ess, port);
Socket tempSocket =
new Socket(ipe.Addr essFamily, SocketType.Stre am,
ProtocolType.Tc p);

tempSocket.Conn ect(ipe);

if(tempSocket.C onnected)
{
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
6578
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 it, the main windows form would still be running in the background and never terminating. How can I terminate the old window form from the new created window. I hope someone out there understands my problem.
20
3007
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 delegate inside the UI that I call to update the progress meter. I use the Suspend() and Abort() methods based on button events. I can watch the progress meter increase just fine when the thread is running. When I select Start, I enable the Cancel...
2
3975
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 TcpListener(IpAddress.Parse("127.0.0.1"), 8080); l.Start(); Socket client = l.AcceptSocket();
6
23726
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); } The problem is that I don't know how to terminate the thread when my class
7
4236
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
7410
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
349
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 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...
3
1164
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 doesn't seem to be the case however with it just dying after one run. I recall there being a Win32 API by the name AttachThreadInput, is this the answer? I'm using the code below to launch the thread.
2
3741
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 to the main form is passed to its constructor. The connection class opens up a new thread and starts doing work in it, and adds collected data to the main form via a (cross-thread) control invoking delegate.
0
8173
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8115
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8568
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6082
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5537
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4047
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4111
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1416
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.