473,883 Members | 1,681 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Asynchronous Sockets and High Async IO Thread Count

Hi there,

Hoping someone could advise me here pls; I'm creating a C# class that
implements a telnet client socket allowing a VB . NET application to
communicate with telnet servers. After leaving the app running for just 6
hrs, the thread count exploded to close to 1000, before the app finally stops
responding. The handles probably hit close to 10000.

Tracing my code, I isolated the leak to when I execute a telnet command.
Everytime I run a telnet command, a thread and several handles are spawned.
After the the command completes, the thread will not die. As I'm unable to
call a EndConnect due to the nature of telnet protocol, could this be giving
me this problem? I tried destroying the telnet client's parent object with a
"Dispose" and "Finalize" and even calling GC, but it still doesn't work out.
The codes attached; hope you can help, thanks!

-------------------------------------------------------------------
public bool Connect()
{
try
{
//connectDone is a ManualResetEven t
connectDone.Res et();

//setup keep-alive heart beats
s.SetSocketOpti on(SocketOption Level.Socket, SocketOptionNam e.KeepAlive,
10);

//attempt an async connection
s.BeginConnect( iep , callbackProc, s );

//wait for 12 sec until connected to host
for (int count=0; count<24; count++)
{
System.Threadin g.Thread.Sleep( 500);
.....
}

catch(SocketExc eption SockEx) { ... }

catch(Exception NormEx) { ... }
.....
}
private void ConnectCallback ( IAsyncResult ar )
{
try
{
// Get The connection socket from the callback
Socket sock1 = (Socket)ar.Asyn cState;
if ( sock1.Connected )
{
connectDone.Set ();
receiveDone.Res et();

// Define a new Callback to read and handle the data
AsyncCallback receiveData = new AsyncCallback( OnReceivedData )

// Begin reading data asynchronously
sock1.BeginRece ive( m_byBuff, 0, m_byBuff.Length , SocketFlags.Non e,
receiveData , sock1 );
}
}
catch( Exception ex )
{
MessageBox.Show ("Setup Receive callbackProc failed!" );
}
}
// This function dispatches a telnet command to the host server
private void SendMessage(str ing strText)
{
try
{
Byte[] smk = new Byte[strText.Length];

for ( int i=0; i < strText.Length ; i++)
{
//doing telnet stuff ...
}

s.SetSocketOpti on(SocketOption Level.Socket, SocketOptionNam e.NoDelay, 0);

//*** callbackProc is a new AsyncCallback(C onnectCallback) delegate
sendDone.Reset( );
ar2 = s.BeginSend(smk , 0 , smk.Length , SocketFlags.Non e ,
callbackProc , s );

//check to ensure that async operation has completed
while (ar2 == null || ar2.IsCompleted == false)
{
System.Threadin g.Thread.Sleep( 500);
}

s.EndSend(ar2);
sendDone.Set();
}

catch(Exception ers) { ... }
}
Nov 22 '05 #1
2 4563
Since this is kind of a "non-typical" application, you might want to look
into a custom ThreadPool where you can control more of what is happening
"under the hood".
Stephen Toub of MS has some excellent code in various recent issues of MSDN
Magazine, or you might look at Ami Bar's "SmartThreadPoo l" over at
codeproject.com
Peter

"brendonlam " <br********@dis cussions.micros oft.com> wrote in message
news:BC******** *************** ***********@mic rosoft.com...
Hi there,

Hoping someone could advise me here pls; I'm creating a C# class that
implements a telnet client socket allowing a VB . NET application to
communicate with telnet servers. After leaving the app running for just 6
hrs, the thread count exploded to close to 1000, before the app finally
stops
responding. The handles probably hit close to 10000.

Tracing my code, I isolated the leak to when I execute a telnet command.
Everytime I run a telnet command, a thread and several handles are
spawned.
After the the command completes, the thread will not die. As I'm unable to
call a EndConnect due to the nature of telnet protocol, could this be
giving
me this problem? I tried destroying the telnet client's parent object with
a
"Dispose" and "Finalize" and even calling GC, but it still doesn't work
out.
The codes attached; hope you can help, thanks!

-------------------------------------------------------------------
public bool Connect()
{
try
{
//connectDone is a ManualResetEven t
connectDone.Res et();

//setup keep-alive heart beats
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.KeepAlive,
10);

//attempt an async connection
s.BeginConnect( iep , callbackProc, s );

//wait for 12 sec until connected to host
for (int count=0; count<24; count++)
{
System.Threadin g.Thread.Sleep( 500);
.....
}

catch(SocketExc eption SockEx) { ... }

catch(Exception NormEx) { ... }
.....
}
private void ConnectCallback ( IAsyncResult ar )
{
try
{
// Get The connection socket from the callback
Socket sock1 = (Socket)ar.Asyn cState;
if ( sock1.Connected )
{
connectDone.Set ();
receiveDone.Res et();

// Define a new Callback to read and handle the data
AsyncCallback receiveData = new AsyncCallback( OnReceivedData )

// Begin reading data asynchronously
sock1.BeginRece ive( m_byBuff, 0, m_byBuff.Length , SocketFlags.Non e,
receiveData , sock1 );
}
}
catch( Exception ex )
{
MessageBox.Show ("Setup Receive callbackProc failed!" );
}
}
// This function dispatches a telnet command to the host server
private void SendMessage(str ing strText)
{
try
{
Byte[] smk = new Byte[strText.Length];

for ( int i=0; i < strText.Length ; i++)
{
//doing telnet stuff ...
}

s.SetSocketOpti on(SocketOption Level.Socket, SocketOptionNam e.NoDelay,
0);

//*** callbackProc is a new AsyncCallback(C onnectCallback) delegate
sendDone.Reset( );
ar2 = s.BeginSend(smk , 0 , smk.Length , SocketFlags.Non e ,
callbackProc , s );

//check to ensure that async operation has completed
while (ar2 == null || ar2.IsCompleted == false)
{
System.Threadin g.Thread.Sleep( 500);
}

s.EndSend(ar2);
sendDone.Set();
}

catch(Exception ers) { ... }
}

Nov 22 '05 #2
Hi Peter,

Thanks for the references; checked them out, but these were on spinning off
new threads for functions. Any way to do the same when I'm dealing with
asynch socket IO? Thanks

brendon lam

"Peter Bromberg [C# MVP]" wrote:
Since this is kind of a "non-typical" application, you might want to look
into a custom ThreadPool where you can control more of what is happening
"under the hood".
Stephen Toub of MS has some excellent code in various recent issues of MSDN
Magazine, or you might look at Ami Bar's "SmartThreadPoo l" over at
codeproject.com
Peter

"brendonlam " <br********@dis cussions.micros oft.com> wrote in message
news:BC******** *************** ***********@mic rosoft.com...
Hi there,

Hoping someone could advise me here pls; I'm creating a C# class that
implements a telnet client socket allowing a VB . NET application to
communicate with telnet servers. After leaving the app running for just 6
hrs, the thread count exploded to close to 1000, before the app finally
stops
responding. The handles probably hit close to 10000.

Tracing my code, I isolated the leak to when I execute a telnet command.
Everytime I run a telnet command, a thread and several handles are
spawned.
After the the command completes, the thread will not die. As I'm unable to
call a EndConnect due to the nature of telnet protocol, could this be
giving
me this problem? I tried destroying the telnet client's parent object with
a
"Dispose" and "Finalize" and even calling GC, but it still doesn't work
out.
The codes attached; hope you can help, thanks!

-------------------------------------------------------------------
public bool Connect()
{
try
{
//connectDone is a ManualResetEven t
connectDone.Res et();

//setup keep-alive heart beats
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.KeepAlive,
10);

//attempt an async connection
s.BeginConnect( iep , callbackProc, s );

//wait for 12 sec until connected to host
for (int count=0; count<24; count++)
{
System.Threadin g.Thread.Sleep( 500);
.....
}

catch(SocketExc eption SockEx) { ... }

catch(Exception NormEx) { ... }
.....
}
private void ConnectCallback ( IAsyncResult ar )
{
try
{
// Get The connection socket from the callback
Socket sock1 = (Socket)ar.Asyn cState;
if ( sock1.Connected )
{
connectDone.Set ();
receiveDone.Res et();

// Define a new Callback to read and handle the data
AsyncCallback receiveData = new AsyncCallback( OnReceivedData )

// Begin reading data asynchronously
sock1.BeginRece ive( m_byBuff, 0, m_byBuff.Length , SocketFlags.Non e,
receiveData , sock1 );
}
}
catch( Exception ex )
{
MessageBox.Show ("Setup Receive callbackProc failed!" );
}
}
// This function dispatches a telnet command to the host server
private void SendMessage(str ing strText)
{
try
{
Byte[] smk = new Byte[strText.Length];

for ( int i=0; i < strText.Length ; i++)
{
//doing telnet stuff ...
}

s.SetSocketOpti on(SocketOption Level.Socket, SocketOptionNam e.NoDelay,
0);

//*** callbackProc is a new AsyncCallback(C onnectCallback) delegate
sendDone.Reset( );
ar2 = s.BeginSend(smk , 0 , smk.Length , SocketFlags.Non e ,
callbackProc , s );

//check to ensure that async operation has completed
while (ar2 == null || ar2.IsCompleted == false)
{
System.Threadin g.Thread.Sleep( 500);
}

s.EndSend(ar2);
sendDone.Set();
}

catch(Exception ers) { ... }
}


Nov 22 '05 #3

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

Similar topics

3
2834
by: Corne Oosthuizen | last post by:
I'm writing a Telnet Server application using Asynchronous sockets. I spawn a listener thread to handel incomming connections and create a separate client socket for each new connection. I then set the new client socket to BeginReceive(). My problem: When two client socket connections send data
2
497
by: brendonlam | last post by:
Hi there, Hoping someone could advise me here pls; I'm creating a C# class that implements a telnet client socket allowing a VB . NET application to communicate with telnet servers. After leaving the app running for just 6 hrs, the thread count exploded to close to 1000, before the app finally stops responding. The handles probably hit close to 10000. Tracing my code, I isolated the leak to when I execute a telnet command. Everytime I...
3
2496
by: Matthew King | last post by:
Hi all I've written a asynchronous socket client class, but i've found that in order to consume it I have to use events, and cannot simply for example SocketClient client = new SocketClient(110, "some.server.com") client.Connect() client.SendData("Hello World") Instead I have to wait for the async method to raise a Connected event, and call client.SendData from there, for complex chains of operations this because a nightmare chain of...
48
5464
by: Steve - DND | last post by:
I'm trying to determine if I need to make my application multi-threaded, or if it can be done with asynchronous programming. I realize that asynch calls do create a new thread in the background, but when they come back, they return to the thread that launched them, is that correct? If I go multi-threaded, then I just need to spawn a new thread for each new connection, right? What I'm doing here is making a service that accepts...
4
5443
by: Matthew Groch | last post by:
Hi all, I've got a server that handles a relatively high number of concurrent transactions (on the magnitude of 1000's per second). Client applications establish socket connections with the server. Data is sent and received over these connections using the asynchronous model. The server is currently in beta testing. Sporadically over the course of the day, I'll observe the thread count on the process (via perfmon) start climbing....
4
3825
by: taskswap | last post by:
I have a legacy application written in C that I'm trying to convert to C#. It processes a very large amount of data from many clients (actually, upstream servers - this is a mux) simultaneously. I've read through what must be dozens of ways to do socket communication in C#, and it seems they all devolve into three basic options - Socket.Select, IOCP through a native interface, and Asynchronous callbacks. I'm fine using Asynchronous...
4
2770
by: Macca | last post by:
I am writing an application that uses asynchronous sockets to get data over ethernet from embedded devices, up to 30 concurrent devices.(These devices are written in C). My application implements an asychronous socket server while the embedded devices are the clients When the data comes in over the socket it is eventually passed into a message queue.
2
2189
by: Ronodev.Sen | last post by:
the way my program needs to go is -- 1) open a socket and listen on it 2) moment a client connects to the socket - process some data (by sending it to another machine), get the result and send it back to the SAME socket - the data isnt a large value (measured in bytes rather than MB or GB) i TRIED thinking of this in the Asynchronous way - BeginReceive - then pass to the OnClient Connected handler, which calls a Wait For Data
4
3611
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket client and asynchronous socket server example code provided in the .NET framework developers guide is a great start but I have not dealt with sockets before and I am struggling with something. From what I can tell the sample server code ...
1
559
by: Navin Mishra | last post by:
Hi, I've an ASP.NET web service that consumes other web services as well as sends data to client using TCP blocking sockets on a custom thread pool threads. If I use asynchronous sockets to send data to clients, would it use threads from ASP.NET IO thread pool ? Is it a good idea ? Or could it potentially exhaust all threads from IO thread pool and cause problems for web service to access other web services ? Thanks in advance and...
0
9940
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
9792
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,...
1
10847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10415
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7971
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
7128
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
5797
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
5991
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4220
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.