473,804 Members | 3,473 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

confused by socket.BeginRec eive

I dont get the point of socket.BeginRec eive and socket.EndRecei ve. As I
understand it, BeginReceive will start a 2nd thread, call the
ReceiveCallback delegate in the 2nd thread, then block until the
socket.EndRecei ve method called in the 2nd thread receives some data
from the socket.

If the 1st thread will block until the 2nd thread receives some data
from the socket, what is the point of starting up the 2nd thread? I am
aware I can create my own thread and have the two threads behave the
way I want, but what am I missing about BeginReceive and EndReceive?

Is BR ... ER intended for situations when a lot of data is to be
received and EndReceive will return after the first block of data is
returned?

A 2nd related question ... How does the first thread kill the receive
in progress in the 2nd thread? Wait for the current chunk of data to
be received by EndReceive and use a sync object of some sort to signal
it is time for the 2nd thread to end?

3rd question ... the documentation says SetSocketOption -
ReceiveTimeout does not apply when Socket.BeginRec eive is used. How do
I implement timeout when using the BeginReceive ... EndReceive pair?

thanks,

-Steve

Nov 17 '05 #1
6 13153
Steve,

I think you are mistaken. When you call BeginReceive, it returns
immediately, and you do not have to wait on the second thread. When the
callback is called, it will be called on the second thread. How you
interact with the first thread is up to you. If you want to have the first
thread wait for the operation to complete, then you can call EndReceive on
the first thread.

As for applying a timeout, you can use an instance of the Timer class in
the System.Timer namespace to do this. After you call BeginReceive, you
start your timer, setting the interval property to the length of time you
want to wait. You also need a flag to indicate if the operation timed out
or not. In the event handler for the callback on the async operation, you
would check the flag. If the flag is set, then do not continue your
processing (since the operation timed out, and there is no need). If the
flag is not set, then disable the timer.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Steve Richter" <St************ @gmail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I dont get the point of socket.BeginRec eive and socket.EndRecei ve. As I
understand it, BeginReceive will start a 2nd thread, call the
ReceiveCallback delegate in the 2nd thread, then block until the
socket.EndRecei ve method called in the 2nd thread receives some data
from the socket.

If the 1st thread will block until the 2nd thread receives some data
from the socket, what is the point of starting up the 2nd thread? I am
aware I can create my own thread and have the two threads behave the
way I want, but what am I missing about BeginReceive and EndReceive?

Is BR ... ER intended for situations when a lot of data is to be
received and EndReceive will return after the first block of data is
returned?

A 2nd related question ... How does the first thread kill the receive
in progress in the 2nd thread? Wait for the current chunk of data to
be received by EndReceive and use a sync object of some sort to signal
it is time for the 2nd thread to end?

3rd question ... the documentation says SetSocketOption -
ReceiveTimeout does not apply when Socket.BeginRec eive is used. How do
I implement timeout when using the BeginReceive ... EndReceive pair?

thanks,

-Steve

Nov 17 '05 #2


Nicholas Paldino [.NET/C# MVP] wrote:
Steve,

I think you are mistaken. When you call BeginReceive, it returns
immediately, and you do not have to wait on the second thread. When the
callback is called, it will be called on the second thread. How you
interact with the first thread is up to you. If you want to have the first
thread wait for the operation to complete, then you can call EndReceive on
the first thread.
ok, thanks Nicholas, I just misread the documentation:

"...Your callback method should implement the EndReceive method. When
your application calls BeginReceive, the system will use a separate
thread to execute the specified callback method, and will block on
EndReceive until the Socket reads data or throws an exception. ..."
As for applying a timeout, you can use an instance of the Timer class in
the System.Timer namespace to do this. After you call BeginReceive, you
start your timer, setting the interval property to the length of time you
want to wait. You also need a flag to indicate if the operation timed out
or not. In the event handler for the callback on the async operation, you
would check the flag. If the flag is set, then do not continue your
processing (since the operation timed out, and there is no need). If the
flag is not set, then disable the timer.


what if the 2nd thread stays blocked on socket.EndRecei ve and does not
return because there is no data to receive? The 2nd thread would
never get to the code that tests the timeout flag.

Can I shutdown the socket in the first thread, which would cause the
socket.EndRecei ve to return?

thanks,

-Steve

Nov 17 '05 #3
Steve,

Basically, in the callback, you call EndReceive to get the results of
the operation. However, your callback will not be executed until the
operation is complete. When your callback is called, EndReceive will return
immediately with the result.

If you call EndReceive before your callback is called, then the thread
you call it (the initial calling thread, perhaps) on will block until the
operation is complete.

If you shut down the socket in the middle of this operation, it should
cause the operation to complete (even because of an abort), and then your
callback will be fired. However, depending on how abrupt the abort call is,
you might have to wrap the call to EndReceive in a try/catch block to catch
any exceptions that arise.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Steve Richter" <St************ @gmail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .


Nicholas Paldino [.NET/C# MVP] wrote:
Steve,

I think you are mistaken. When you call BeginReceive, it returns
immediately, and you do not have to wait on the second thread. When the
callback is called, it will be called on the second thread. How you
interact with the first thread is up to you. If you want to have the
first
thread wait for the operation to complete, then you can call EndReceive
on
the first thread.


ok, thanks Nicholas, I just misread the documentation:

"...Your callback method should implement the EndReceive method. When
your application calls BeginReceive, the system will use a separate
thread to execute the specified callback method, and will block on
EndReceive until the Socket reads data or throws an exception. ..."
As for applying a timeout, you can use an instance of the Timer class
in
the System.Timer namespace to do this. After you call BeginReceive, you
start your timer, setting the interval property to the length of time you
want to wait. You also need a flag to indicate if the operation timed
out
or not. In the event handler for the callback on the async operation,
you
would check the flag. If the flag is set, then do not continue your
processing (since the operation timed out, and there is no need). If the
flag is not set, then disable the timer.


what if the 2nd thread stays blocked on socket.EndRecei ve and does not
return because there is no data to receive? The 2nd thread would
never get to the code that tests the timeout flag.

Can I shutdown the socket in the first thread, which would cause the
socket.EndRecei ve to return?

thanks,

-Steve

Nov 17 '05 #4


Nicholas Paldino [.NET/C# MVP] wrote:
If you call EndReceive before your callback is called, then the thread
you call it (the initial calling thread, perhaps) on will block until the
operation is complete.
Is this a guarantee? I couldn't find that anywhere in the docs when I
last did async IO.
If you shut down the socket in the middle of this operation, it should
cause the operation to complete (even because of an abort), and then your
I have never seen Thread.Abort actually abort a call on a blocking
socket. I have seen the Close of a socket generate an exception in
EndReceive though.
callback will be fired. However, depending on how abrupt the abort call is,
you might have to wrap the call to EndReceive in a try/catch block to catch
any exceptions that arise.


I don't see it as special. You have to be aware, that the socket
EndReceive is associated with might be invalid when you get invoked (it
was Close()'ed elsewhere) though.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #5


Steve Richter wrote:
I dont get the point of socket.BeginRec eive and socket.EndRecei ve. As I
understand it, BeginReceive will start a 2nd thread, call the


A piece of advice: unless you *really* *really* need non-blocking IO,
don't use it. The potential synchroniazatio n problems are *huge*.

If you do decide to go for it for some reason, like performance, write a
test that validates that you actually realize your reason (I've seen a
few places where async-IO was a lot slower than blocking).

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #6
Helge Jensen <he**********@s log.dk> wrote:
Nicholas Paldino [.NET/C# MVP] wrote:
If you call EndReceive before your callback is called, then the thread
you call it (the initial calling thread, perhaps) on will block until the
operation is complete.


Is this a guarantee? I couldn't find that anywhere in the docs when I
last did async IO.


It depends exactly what you mean by "operation is complete", but from
the docs:

<quote>
The EndReceive method will block until data is available. If you are
using a connectionless protocol, EndReceive will read the first
enqueued datagram available in the incoming network buffer. If you are
using a connection-oriented protocol, the EndReceive method will read
as much data as is available up to the number of bytes you specified in
the size parameter of the BeginReceive method
</quote>

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7

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

Similar topics

2
9236
by: dream machine | last post by:
Hi all , with BegeinReceive I can build async method of Socket Class that Receive the data from the Socket Client . My question is , if I have this code that create 3 Receive Async Call : <code> mySocket.BeginReceive(param1,param2,param3.....); mySocket.BeginReceive(param1,param2,param3......); mySocket.BeginReceive(param1,param2,param3......);
4
7594
by: Brian Rice | last post by:
I have a socket application that is sending and receiving packets asynchronously. It works great except, when I receive packets that are larger than my receive buffer which then generate several EndReceive calls... these calls seem to be sometimes coming out of order. For example, the following is from my log file: Connection at 5/1/2004 11:39:14 AM SENT> ZZZ:1:FMZZZ:ID1234:PWAAAA:VR100:\0 RCVD>...
1
3400
by: John Sheppard | last post by:
Thanks to everyone that responded to my previous Socket Programming question. Now I have run into some behavior that I don't quite understand. Programming environment. VS.NET 2003, C#, Windows XP. About the architecture: I have a socket server dll that contains a class that handles connections for a given local ipaddress and port. This class(server) can be started or stopped by calls to the appropriate functions. The server class has...
7
2389
by: Colin | last post by:
I'm writing a little console socket server but I'm having some difficulty. Can I ask your advice - where is the best place to get some help on that topic? It would be nice if some people who knew what they were doing could take a look at my code and tell me where and why I'm going wrong. Any suggestions of groups or forums?
1
2561
by: Marty | last post by:
Hi, I have a socket that always seek for incoming data. Between Point A and Point B, the socket (mySocket is closed and assigned to nothing in another part of my program (happen when a connection is broken). So regurlarly when a socket is closed, it create an error somewhere in this routine, even if I check if the socket is nothing or not, and connected or not (I also tried to check before doing the beginreceive)
9
3609
by: Macca | last post by:
Hi, I have a synchronous socket server which my app uses to read data from clients. To test this I have a simulated client that sends 100 byte packets. I have set up the socket server so that its buffer is bigger than this. I did this expecting the data to be read in one pass.
0
4694
by: Macca | last post by:
Hi, I am writing an asychronous socket server to handle 20+ simulataneous connections. I have used the example in MSDN as a base. The code is shown at end of question. Each connection has a number of different types of data coming in. I have a databuffer for each type of data coming in.
2
6544
by: O.B. | last post by:
In the following code snippet, the thread successfully makes it to the line where it waits for data to be received. Then the client closes the connection. The thread wakes up and returns from the WaitOne() operation. No exception is thrown when it loops and executes BeginReceive() again. The WaitOne() operation returns immediately. Thus, there's an endless loop. How does one detect that the remote client has closed the connection in...
6
7008
by: Pat B | last post by:
Hi, I'm writing my own implementation of the Gnutella P2P protocol using C#. I have implemented it using BeginReceive and EndReceive calls so as not to block when waiting for data from the supernode. Everything I have written works fine sending and receiving uncompressed data. But now I want to implement compression using the deflate algorithm as the Gnutella protocol accepts: Accept-Encoding: deflate Content-Encoding: deflate in the...
0
9705
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
9576
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
10323
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...
1
10311
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
9138
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
7613
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
5647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3813
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2988
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.