473,970 Members | 17,763 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question abut threads

I am working on a program that creates a few TCP listenrs to accept data
from non .net processes.
Each listener listens in its own thread. I am using Thread.Sleep(10 00) to
let other threads work.
Here is my code:
tcpl = new TcpListener(ipe );
TcpClient tcpc = tcpl.AcceptTcpC lient();
while (true)
{
// get data
while (true)
{
// if contidion met break;
}
Thread.Sleep(10 00) ;
}

Do I really need Thread.Sleep(10 00) ? What would happend if I dont use it at
all?

Thanks
Aug 7 '08 #1
21 1540
On Aug 7, 1:25*pm, "Markgoldin " <markgoldin_2.. .@yahoo.comwrot e:
I am working on a program that creates a few TCP listenrs to accept data
from non .net processes.
Each listener listens in its own thread. I am using Thread.Sleep(10 00) to
let other threads work.
Here is my code:
tcpl = new TcpListener(ipe );
TcpClient tcpc = tcpl.AcceptTcpC lient();
while (true)
{
* * // get data
* * while (true)
* * {
* * * * // if contidion met break;
* * }
* * Thread.Sleep(10 00) ;

}

Do I really need Thread.Sleep(10 00) ? What would happend if I dont use itat
all?
That depends on what happens in the loop. Are you actually likely to
be processor bound? Is your while loop a tight loop? If so, that's the
thing to fix.

It's unlikely that you should really be sleeping, but if you ever need
to wait for a condition to be met, you should probably be using an
Auto/ManualResetEven t or Monitor.Wait/Pulse.

Jon
Aug 7 '08 #2
On Aug 7, 8:25*am, "Markgoldin " <markgoldin_2.. .@yahoo.comwrot e:
I am working on a program that creates a few TCP listenrs to accept data
from non .net processes.
Each listener listens in its own thread. I am using Thread.Sleep(10 00) to
let other threads work.
you should only do this if each listener listen in a different post.

Here is my code:
tcpl = new TcpListener(ipe );
TcpClient tcpc = tcpl.AcceptTcpC lient();
while (true)
{
* * // get data
* * while (true)
* * {
* * * * // if contidion met break;
* * }
* * Thread.Sleep(10 00) ;

}

Do I really need Thread.Sleep(10 00) ? What would happend if I dont use itat
all?
why you use it in the first place??

Answer to this, are you using one port or multiple ports?
I can give you code in each case, it's as simple as using a SyncQueue.
and one thread per connection (no per listener)
Aug 7 '08 #3
On Thu, 07 Aug 2008 08:04:03 -0700, Ignacio Machin ( .NET/ C# MVP )
<ig************ @gmail.comwrote :
On Aug 7, 8:25Â*am, "Markgoldin " <markgoldin_2.. .@yahoo.comwrot e:
>I am working on a program that creates a few TCP listenrs to accept data
from non .net processes.
Each listener listens in its own thread. I am using Thread.Sleep(10 00)
to
let other threads work.

you should only do this if each listener listen in a different post.
I believe Ignacio has a one-letter type here: "post" should be "port".
Hopefully that was clear from the rest of his message, but if not this
should clear it up. :)
[...]
>Do I really need Thread.Sleep(10 00) ? What would happend if I dont use
it at
all?

why you use it in the first place??

Answer to this, are you using one port or multiple ports?
I can give you code in each case, it's as simple as using a SyncQueue.
and one thread per connection (no per listener)
I don't find the type "SyncQueue" in the MSDN documentation, so I don't
know what Ignacio is getting at. That said, I'll suggest that there are
really only two viable approaches to TCP network i/o in .NET:

-- one thread per connection, using blocking i/o
-- asynchronous API (e.g. Socket.BeginRec eive(), etc.)

(For i/o using the Socket class directly, there is a Select() method
similar to BSD sockets's select() function which is theoretically simpler
than the asynchronous API, but personally I think it's both awkward and
inefficient. .NET has much better i/o paradigms to take advantage of).

The former can be the simplest, assuming each connection is completely
independent from each other. But it's only appropriate for relatively
small numbers of remote endpoints (hundreds, at the very most). The
latter is much more scalable, and more importantly, most implementations
other than the "one thread per connection" design are going to wind up
involving some similar thread management issues anyway. One might as well
use the built-in threaded i/o rather than reinventing the wheel.

MSDN has code samples for the asynchronous API both in the Socket class
and, if I recall correctly, the TcpListener/TcpClient classes.

Pete
Aug 7 '08 #4
On Aug 7, 12:34*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Thu, 07 Aug 2008 08:04:03 -0700, Ignacio Machin ( .NET/ C# MVP ) *

<ignacio.mac... @gmail.comwrote :
On Aug 7, 8:25*am, "Markgoldin " <markgoldin_2.. .@yahoo.comwrot e:
I am working on a program that creates a few TCP listenrs to accept data
from non .net processes.
Each listener listens in its own thread. I am using Thread.Sleep(10 00)*
to
let other threads work.
you should only do this if each listener listen in a different post.

I believe Ignacio has a one-letter type here: "post" should be "port". *
Hopefully that was clear from the rest of his message, but if not this *
should clear it up. *:)
Sorry for the mistake, I also noticed a couple of words in spanish in
another post, I've been without coffee the entire morning, not good
for health :)
I don't find the type "SyncQueue" in the MSDN documentation, so I don't *
know what Ignacio is getting at. *That said, I'll suggest that there are *
really only two viable approaches to TCP network i/o in .NET:

There is none, but you have Queue.Synchroni zed method:
Returns a Queue wrapper that is synchronized (thread safe).

Seet his example:
Queue connectionQueue ;
protected override void OnStart(string[] args)
{
listenerThread = new Thread( new ThreadStart( ListenerMethod) );
listenerThread. Start();
}
protected void ListenerMethod( )

{
Thread workingthread;
Queue unsyncq = new Queue();
connectionQueue = Queue.Synchroni zed( unsyncq);
TcpClient socket;
TcpListener listener = new TcpListener( 1212);

listener.Start( );
while( true)
{
socket = listener.Accept TcpClient();
connectionQueue .Enqueue( socket);
workingthread = new Thread( new
ThreadStart( TheConnectionHa ndler));
workingthread.S tart();
}
}
public void TheConnectionHa ndler()
{
TcpClient socket= (TcpClient)conn ectionQueue.Deq ueue();
//use the socket
}
Aug 7 '08 #5
On Thu, 07 Aug 2008 11:18:01 -0700, Ignacio Machin ( .NET/ C# MVP )
<ig************ @gmail.comwrote :
[...]
>I don't find the type "SyncQueue" in the MSDN documentation, so I don't
know what Ignacio is getting at. Â*That said, I'll suggest that there
are Â*
really only two viable approaches to TCP network i/o in .NET:

There is none, but you have Queue.Synchroni zed method:
Returns a Queue wrapper that is synchronized (thread safe).

Seet his example:
All due respect and no offense intended, but... yuck! :)

You're using the queue just as a way of passing data from one thread to
another? What's wrong with using ParameterizedTh readStart? For example:

protected void ListenerMethod( )
{
TcpListener listener = new TcpListener(121 2);

listener.Start( );
while (true)
{
TcpClient client = listener.Accept TcpClient();

new Thread(TheConne ctionHandler).S tart(client);
}
}

protected void TheConnectionHa ndler(object objArg)
{
TcpClient client = (TcpClient)objA rg;

//...
}

Notes:

-- I prefer to use the variable name "socket" only when it's actually
a Socket instance. TcpClient wraps a Socket, and can be used in similar
ways. But it's not really a Socket and thinking it is could lead to some
confusion.

-- The compiler can infer the correct type for the Thread constructor
and create the delegate for you, so you don't actually need to explicitly
specify "new ThreadStart(... )" or "new ParameterizedTh readStart(...)" when
creating the Thread instance.

A slight variation on the above theme would be to capture the "client"
variable in an anonymous method and avoid casting altogether:

protected void ListenerMethod( )
{
TcpListener listener = new TcpListener(121 2);

listener.Start( );
while (true)
{
TcpClient client = listener.Accept TcpClient();

new Thread(delegate { TheConnectionHa ndler(client) }).Start();
}
}

protected void TheConnectionHa ndler(TcpClient client)
{
//...
}

I still prefer the asynchronous methods. But the above are, I think, at
least more appropriate than creating a queue just for the purpose of
moving a single reference from one thread to another.

Just my two cents.

Pete
Aug 7 '08 #6
On Thu, 07 Aug 2008 11:33:48 -0700, Peter Duniho
<Np*********@nn owslpianmk.comw rote:
[...]
new Thread(delegate { TheConnectionHa ndler(client)
}).Start();
Sorry...forgot a semi-colon there. I assume the reader can easily fix
that, but just in case:

new Thread(delegate { TheConnectionHa ndler(client); }).Start();
Aug 7 '08 #7
Instead of using threads to keep client state, you may want to look into
using async comm. The fx3.5 has some improvements in socket class that may
help:
http://msdn.microsoft.com/en-us/magazine/cc163356.aspx
--wjs

"Markgoldin " <ma************ *@yahoo.comwrot e in message
news:eV******** ********@TK2MSF TNGP06.phx.gbl. ..
>I am working on a program that creates a few TCP listenrs to accept data
from non .net processes.
Each listener listens in its own thread. I am using Thread.Sleep(10 00) to
let other threads work.
Here is my code:
tcpl = new TcpListener(ipe );
TcpClient tcpc = tcpl.AcceptTcpC lient();
while (true)
{
// get data
while (true)
{
....

Aug 8 '08 #8
On Aug 7, 2:33*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Thu, 07 Aug 2008 11:18:01 -0700, Ignacio Machin ( .NET/ C# MVP ) *

<ignacio.mac... @gmail.comwrote :
[...]
I don't find the type "SyncQueue" in the MSDN documentation, so I don't *
know what Ignacio is getting at. *That said, I'll suggest that there*
are *
really only two viable approaches to TCP network i/o in .NET:
There is none, but you have Queue.Synchroni zed *method:
Returns a Queue wrapper that is synchronized (thread safe).
Seet his example:

All due respect and no offense intended, but... *yuck! *:)

You're using the queue just as a way of passing data from one thread to *
another? *What's wrong with using ParameterizedTh readStart? *For example:
No offense taken :)

You are right, you can use ParameterizedTh readStart . The thing is
that that piece of code is from 1.1 era , you had no
ParameterizedTh readStart back then :)
This is the original post:

http://groups.google.com/group/micro...eabe586c0924e0

Just recently I updated it to 2005 but the code is the same, it works,
so why change it ? :)
* * *protected void ListenerMethod( )
* * *{
* * * * *TcpListener listener = new TcpListener(121 2);

* * * * *listener.Start ();
* * * * *while (true)
* * * * *{
* * * * * * *TcpClient client = listener.Accept TcpClient();

* * * * * * *new Thread(delegate { TheConnectionHa ndler(client) }).Start();
* * * * *}
* * *}

* * *protected void TheConnectionHa ndler(TcpClient client)
* * *{
* * * * *//...
* * *}
That would be the best solution :)
Aug 8 '08 #9
On Fri, 08 Aug 2008 08:03:54 -0700, Ignacio Machin ( .NET/ C# MVP )
<ig************ @gmail.comwrote :
[...]
Just recently I updated it to 2005 but the code is the same, it works,
so why change it ? :)
For your own use? I see no reason to change it. For the purpose of
providing suggestions to others? I'm sure you can figure out what _I_
think... :)

For what it's worth, even in 1.1 I think there are better approaches. For
example:

class MainClass
{
// Since in 1.1 we wouldn't have this delegate type, define
// it ourselves.
delegate void ParameterizedTh readStart(objec t objParameter);

class ThreadWithParam eter
{
ParameterizedTh readStart _start;
object _objParameter;

public ThreadWithParam eter(Parameteri zedThreadStart start,
object objParameter)
{
_start = start;
_objParameter = objParameter;
}

public void StartMethod()
{
_start(_objPara meter);
}
}

void MethodThatStart sThread()
{
object objParameter = new object(); // or whatever you want
ThreadWithParam eter twp =
new ThreadWithParam eter(
new ParameterizedTh readStart(Desir edThreadStart),
objParameter);

new Thread(new ThreadStart(twp .StartMethod)). Start();
}

void DesiredThreadSt art(object objParameter)
{
// do some work in a thread
}
}

(The "ThreadWithPara meter" class doesn't actually need to be nested as
above. Though, if you want to tie the class more closely to whatever code
is actually running the thread, that could make it more convenient).

To me, using a synchronized Queue makes a lot of sense if you're starting
multiple threads with the same entry point but each with different input.
But otherwise, it seems like overkill at best, and maybe a bit confusing
and misleading at worst. It's not _terrible_ in any case, but it does
seem awkward and not very expressive. :)

Pete
Aug 8 '08 #10

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

Similar topics

0
2080
by: Dean Speir | last post by:
Hoping that someone here can see the glitch I'm experiencing. I build a site for an organization in which a <TD> which recurs on most of the pages displays exactly as intended in IE, Netscape and Firefox. It is seen here: http://www.lipsa.net/, and the external style sheet is at http://www.lipsa.net/pbr.css. Note how the dark green TD "sidebar" on the right of the screen flushes all the way to the right, and up against both the top and...
2
1478
by: grahamo | last post by:
Hi, I realise that c++ knows nothing about threads however my question is related to an (excellent) article I was reading about threads and C++. For all intents and purposes we can forget the sample at hand is concerned about threads, it could be related to widgets for the purpose of this question (that's so I don't get flamed and told to go to comp.programming.threads :)
11
4289
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate threads of a multithreaded program using embedded SQL. Since the threads do not need to share transaction scopes, the sqleAttachToCtx family of APIs do not seem to be necessary. <quote> In the default implementation of threaded applications against...
5
276
by: Timur | last post by:
Hi gurus, I have a problem to convert MS SQL Server application to DB2. I have a view which combines 7 tables ( table sizes 60millions rows, 3 mill, 1 mill, other small ones) I use this view to populate OLAP cube and in SQL Server it takes abut 1 hour.. In DB2 it takes forever. Execution plan looks ugly - DB2 sorts !!!!! 50 mil table by field which is key field for 3 mill rows table. Indexes are in place, I updated statistics. When I...
1
1105
by: serge calderara | last post by:
Dear all, When I place a datagrid server control on a webform by default it shows 3 columns My application makes runtime data binding to a table in database. So far it works well all my column present on my bind dataset gets displayed properly. Then I try to use template on Column 0 abut when I run my application again, the fact of adding a template to column 0 has add an extra column before the column 0..
4
3470
by: Rui Maciel | last post by:
I'm trying to go through the elements of a STL list container in such a way that each element can be acessed along with each and every subsequent element from the list. For example, let's say I have the following list: A B C D E F G H... What I am trying to do is something like this: AB, AC, AD, AE, ... , BC, BD, BE, ... , CD, CE, ...
9
1787
by: Gilbert | last post by:
Hi, In the code-behind, i have this function: Public Function myfunction(ByVal myvar As Object) As String dim x as string = myvar ..... Return x End Function
3
2002
by: Chris Roth | last post by:
I'm using VS.net 7.1 on Windows XP. I have a class that hold a container of doubles. One function (foo) for the class calls a sub-function (bar) for each of the doubles. I'd like to multithread foo so that the bar sub-functions can run on multiple threads. I'd like to imlpement this with _beginthreadex as I'm using std::vector. Please provide some working code around the following details: #include <windows.h // for HANDLE...
19
1832
by: frankiespark | last post by:
Hello all, I was perusing the internet for information on threading when I came across this group. Since there seems to be a lot of good ideas and useful info I thought I'd pose a question. Threading is a new concept for me to implement. Here is my problem. I have a system that receives xml files and records their file locations in a database. I can potentially receive thousands,
0
10345
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
10157
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
11398
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
10897
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...
0
10065
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...
0
7595
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
6400
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...
1
5140
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3748
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.