471,594 Members | 1,872 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

can I use IAsyncResult.IsCompleted Property to know if Endxxx was already called?

Hi all,
someone know if I can use the IAsyncResult.IsCompleted Property of
IAsyncResult that return from Socket.Beginxxx methods to determine if the
Endxxx method already called perior or not ?
I have methods that return the IAsyncResult after I called begin... (connect
for example)
and I want to know if I should call the EndConnect or not outside the
method.
Thanks
Oct 25 '06 #1
12 4423
Hi,

You should always call EndConnect regardless.

--
Dave Sexton

"semedao" <se*****@community.nospamwrote in message
news:%2******************@TK2MSFTNGP05.phx.gbl...
Hi all,
someone know if I can use the IAsyncResult.IsCompleted Property of
IAsyncResult that return from Socket.Beginxxx methods to determine if the
Endxxx method already called perior or not ?
I have methods that return the IAsyncResult after I called begin... (connect
for example)
and I want to know if I should call the EndConnect or not outside the
method.
Thanks

Oct 25 '06 #2
Hi Semedao,

Based on my understanding, your main thread is performing some asynchronous
socket operations with Socket.BeginXXX methods. After calling
Socket.BeginXXX method in this main thread , you want to know if you should
check the IAsyncResult.IsCompleted property to determine the operation is
complete so that there is no need to call Endxxx method in the main thread.
If I have misunderstood your problem context, please feel free to tell me,
thanks.

Normally, in the Socket Asynchronous programming model, before you call
Socket.BeginConnect, you can create acallback method that implements the
AsyncCallback delegate and pass its name to the BeginConnect method as
second parameter. This callback method will execute in a separate thread
and is called by the system after BeginConnect returns. The callback method
must accept the IAsyncResult returned by the BeginConnect method as a
parameter. And after obtaining the Socket in the callback method, you can
call the EndConnect method to successfully complete the connection attempt.
Note: the EndConnect is executed in the threadpool thread and will block
until connected.

So there is no need for your main thread to call EndConnect method, but it
is the callback method executed in the threadpool thread that should call
EndConnect method.

I think your main concern may be that: in the main thread, after calling
Socket.BeginXXX method, what should you do to know that the operation is
finished. Since the callback thread knows the operation status, normally,
you may use an event to synchronize and communicate between your main
thread and the callback executing thread. The sample code in the article
below demonstrates the logic
"Asynchronous Client Socket Example"
http://msdn2.microsoft.com/en-us/library/bew39x2a.aspx

Finally, if you want to know the internal work, by using Reflector, you
will see that, Socket.EndConnect method mainly calls
LazyAsyncResult.WaitForCompletion(true), whose key code snippet is listed
below:

private object WaitForCompletion(bool snap)
{
ManualResetEvent event1 = null;
bool flag1 = false;
if (!(snap ? this.IsCompleted : this.InternalPeekCompleted))
{
event1 = (ManualResetEvent) this.m_Event;
if (event1 == null)
{
flag1 = this.LazilyCreateEvent(out event1);
}
}
.....
try
{
event1.WaitOne(-1, false);
......
}

Yes, this method checks "IsCompleted" property, if it is true,
Socket.EndConnect method will return without sleeping. If not, it means the
connect operation is still pending, it will obtain the internal "m_Event"
and wait on this event to signal. Note: "m_Event" is created in the
Socket.BeginConnect method and will be signaled when the asynchronous
operation completes.

So Socket.EndConnect method really checks "IsCompleted" property
internally, however, it will eliminate our loop checking on "IsCompleted"
property, but wait on an internal event to get notification.

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Oct 26 '06 #3
Hi ,
I know , but the question is how to determine if I already called Endconnect
for this socket in other place
instead of writing some flags , I want to use something in the
IasyncResult..
because calling EndConnect second time will throw exception.
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:%2******************@TK2MSFTNGP05.phx.gbl...
Hi,

You should always call EndConnect regardless.

--
Dave Sexton

"semedao" <se*****@community.nospamwrote in message
news:%2******************@TK2MSFTNGP05.phx.gbl...
>Hi all,
someone know if I can use the IAsyncResult.IsCompleted Property of
IAsyncResult that return from Socket.Beginxxx methods to determine if the
Endxxx method already called perior or not ?
I have methods that return the IAsyncResult after I called begin...
(connect for example)
and I want to know if I should call the EndConnect or not outside the
method.
Thanks


Oct 27 '06 #4
Hi Semedao,

Have you read Jeffrey's article?

--
Dave Sexton

"semedao" <se*****@community.nospamwrote in message
news:eg****************@TK2MSFTNGP02.phx.gbl...
Hi ,
I know , but the question is how to determine if I already called Endconnect
for this socket in other place
instead of writing some flags , I want to use something in the
IasyncResult..
because calling EndConnect second time will throw exception.
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:%2******************@TK2MSFTNGP05.phx.gbl...
>Hi,

You should always call EndConnect regardless.

--
Dave Sexton

"semedao" <se*****@community.nospamwrote in message
news:%2******************@TK2MSFTNGP05.phx.gbl. ..
>>Hi all,
someone know if I can use the IAsyncResult.IsCompleted Property of
IAsyncResult that return from Socket.Beginxxx methods to determine if the
Endxxx method already called perior or not ?
I have methods that return the IAsyncResult after I called begin...
(connect for example)
and I want to know if I should call the EndConnect or not outside the
method.
Thanks



Oct 27 '06 #5
Hi Semedao,

How about this issue now? Is it resolved? If you still need any help or
have any concern, please feel free to feedback, thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 1 '06 #6
Hi Jeffrey
first , tanks for your answer
I think I need to explain my "big" problem...
I try to make a connection between 2 peers behind 2 Nats
what called: "hole punching"
based on the article in:
http://www.brynosaurus.com/pub/net/p2pnat/
we need to start async connect calls from both peers to each other.
It was already work for me in some routers test
until I came to router that does not return me "refused" exception imidiatly
on this type of router that does not return nothing.. the peer that made the
"beginConnect" will wait for (in my comp) 20-21 seconds , until he can make
the next beginconnect
this will break the all hole punching... , because I need to send "syn_sent"
to the other peer every short period (like 1 second)
this was the reason to try playing with the asyncresult
If I start new socket before endconnect complete and make beginconnect it
will throw exception of
"SocketException : System.Net.Sockets.SocketException: Only one usage of
each socket address (protocol/network address/port) is normally permitted"
It happen also when I use the
_socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);

or

_socket.ExclusiveAddressUse = false;

I try to make

ar.AsyncWaitHandle.WaitOne(1000,false);

In the calling thread of the BeginConnect after the call , and :

_socket.Shutdown(SocketShutdown.Both);

_socket.Close();

or

_socket.Disconnect(false);

before create the new Socket for the next beginConnect

also I try to set the

_socket.SendTimeout = 1000;

_socket.ReceiveTimeout = 1000;

values , thinking thatit will raise to me the SocketException of timeout
after only 1 second...

nothing work...

so , I am stack here with this problem...

If I had some option to call the next beginConnect that even if fail - will
success to send the "syn_sent" to the remote peer in some way - it can solve
me the problem

Thanks

""Jeffrey Tan[MSFT]"" <je***@online.microsoft.comwrote in message
news:QT**************@TK2MSFTNGXA01.phx.gbl...
Hi Semedao,

How about this issue now? Is it resolved? If you still need any help or
have any concern, please feel free to feedback, thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no
rights.

Nov 6 '06 #7
Hi,
I just discussed with Jeffery and we think that we have not totally
understood your issue. Te let us better understand your issue, could you
please answer me some questions?
1. What did you mean that you could call next BeginConnect after 20s?
2. Did all BeginConnect methods connect to the same endpoint?
3. How did you send the "syn_sent" to the endpoint if the connection had
not been established?
4. Why did you want to break the connection after 1s since it had not been
established? Wouldn't it also fail when the next BeginConnect was invoked?
5. Could you please mail me (ch******@microsoft.com) a sample project for
further research?

Sincerely yours,
Charles Wang
Microsoft Online Community Support

================================================== ====
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from this issue.
================================================== ====
This posting is provided "AS IS" with no warranties, and confers no rights.
================================================== ====
Nov 7 '06 #8
Hi Semedao,
Just check to see if you are still paying attention on this issue. We are
interested in this issue. If you could post back and let us know this issue
more detailed, we will be very glad and encouraged to assist further.

Though this issue is hard to troubleshoot due to its complexity and only
some routers leading to this problem, your detailed information will prompt
our understanding and research on this issue so that we can piont out a
direction to you. If we found that this issue is really hard to be resolved
at our newsgroup, we will escalate you to a senior team for best support.

If you have any other questions or concerns, please feel free to let me
know. I will be more that happy to be of assistance.

Sincerely yours,
Charles Wang
Microsoft Online Community Support

Nov 9 '06 #9
Hi,

Nice article, thanks for the link.
ar.AsyncWaitHandle.WaitOne(1000,false);

In the calling thread of the BeginConnect after the call , and :

_socket.Shutdown(SocketShutdown.Both);

_socket.Close();

or

_socket.Disconnect(false);

before create the new Socket for the next beginConnect
What is preventing you from using this approach? Is there an exception being
thrown? What is it?

The following code should work:

IAsyncResult ar = socket.BeginConnect(...);

if (!ar.AsyncWaitHandle.WaitOne(1000, false))
socket.Close();

Realize that the connection may have been established if you waited longer,
but the timeout will expire after one second regardless (even if this isn't
true in the particular case you are testing it could be true in others). Due
to network latency and its indeterministic nature, it's possible that
subsequent attempts will fail the same, although given enough time would
complete successfully. The timeout of one second might be too restrictive
(although I'd imagine not in most circumstances now that dial-up is becoming
less and less commonplace in home networks; I hope :). I don't believe that
the timeout of one second is required for "hole punching" either. One second
is simply used as an example in the article [§4.2 Opening Peer-to-Peer TCP
Streams].

You may want to allow the connection to timeout. If it's not working still
then it's possible that the NAT isn't behaving according to hole-punching
requirements.
also I try to set the

_socket.SendTimeout = 1000;

_socket.ReceiveTimeout = 1000;
These timeouts only apply to the Send and Receive methods (not the Begin*
methods). And I don't believe there is a timeout setting available for the
Connect method (or BeginConnect).

--
Dave Sexton

"semedao" <se*****@community.nospamwrote in message
news:uM**************@TK2MSFTNGP03.phx.gbl...
Hi Jeffrey
first , tanks for your answer
I think I need to explain my "big" problem...
I try to make a connection between 2 peers behind 2 Nats
what called: "hole punching"
based on the article in:
http://www.brynosaurus.com/pub/net/p2pnat/
we need to start async connect calls from both peers to each other.
It was already work for me in some routers test
until I came to router that does not return me "refused" exception imidiatly
on this type of router that does not return nothing.. the peer that made the
"beginConnect" will wait for (in my comp) 20-21 seconds , until he can make
the next beginconnect
this will break the all hole punching... , because I need to send "syn_sent"
to the other peer every short period (like 1 second)
this was the reason to try playing with the asyncresult
If I start new socket before endconnect complete and make beginconnect it
will throw exception of
"SocketException : System.Net.Sockets.SocketException: Only one usage of
each socket address (protocol/network address/port) is normally permitted"
It happen also when I use the
_socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);

or

_socket.ExclusiveAddressUse = false;

I try to make

ar.AsyncWaitHandle.WaitOne(1000,false);

In the calling thread of the BeginConnect after the call , and :

_socket.Shutdown(SocketShutdown.Both);

_socket.Close();

or

_socket.Disconnect(false);

before create the new Socket for the next beginConnect

also I try to set the

_socket.SendTimeout = 1000;

_socket.ReceiveTimeout = 1000;

values , thinking thatit will raise to me the SocketException of timeout
after only 1 second...

nothing work...

so , I am stack here with this problem...

If I had some option to call the next beginConnect that even if fail - will
success to send the "syn_sent" to the remote peer in some way - it can solve
me the problem

Thanks

""Jeffrey Tan[MSFT]"" <je***@online.microsoft.comwrote in message
news:QT**************@TK2MSFTNGXA01.phx.gbl...
>Hi Semedao,

How about this issue now? Is it resolved? If you still need any help or
have any concern, please feel free to feedback, thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
================================================= =
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
================================================= =
This posting is provided "AS IS" with no warranties, and confers no rights.


Nov 10 '06 #10
Hi Charles & Jeffrey , sorry that I replay only now
1. I call the next BeginConnect AFTER the first one EndConnect return , when
the other side doesn't return nothing , I will block on the EndConnect until
TimeOut occure.. it's take 20~ sec

2. Yes (I use socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);)
3. the BeginConnect make it
4. I want because when trying to make hole punch both peers need to send
async syn_sent (beginconnect) to the other in short period - this is the
reason I don't want to block for 20~ seconds on the EndConnect

I already solve it by call to socket.close and socket = null after 1+ sec if
the asyncresult did not signald
but still the hole punch does not work on this situation evenif I send a lot
of syn_sent...

Do you know what is hole punch ?
take a look in the article I sent before
also , if you have some link for free code that make hole punch in c# can be
great
thanks again

"Charles Wang[MSFT]" <ch******@online.microsoft.comwrote in message
news:zl**************@TK2MSFTNGXA01.phx.gbl...
Hi,
I just discussed with Jeffery and we think that we have not totally
understood your issue. Te let us better understand your issue, could you
please answer me some questions?
1. What did you mean that you could call next BeginConnect after 20s?
2. Did all BeginConnect methods connect to the same endpoint?
3. How did you send the "syn_sent" to the endpoint if the connection had
not been established?
4. Why did you want to break the connection after 1s since it had not been
established? Wouldn't it also fail when the next BeginConnect was invoked?
5. Could you please mail me (ch******@microsoft.com) a sample project for
further research?

Sincerely yours,
Charles Wang
Microsoft Online Community Support

================================================== ====
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from this issue.
================================================== ====
This posting is provided "AS IS" with no warranties, and confers no
rights.
================================================== ====


Nov 12 '06 #11
Hi,

Have you considered that the NAT you are testing doesn't behave in such a way
that hole-punching will work?

Here's a line from the article that you linked us to:

"64% [of tested NATs] support hole punching for TCP streams"

Hole-punching is a hack, and therefore it comes with no guarantees. Once it's
standardized (if ever) then you should start to see an improvement in the
distribution of NATs that exhibit the required behavior.

For now, you might have to find a different hack that works for you :)

Of course, I'm against hacks in the first place. I suggest asking the owner
of the NAT to open the required ports.

--
Dave Sexton

"semedao" <se*****@community.nospamwrote in message
news:eP**************@TK2MSFTNGP04.phx.gbl...
Hi Charles & Jeffrey , sorry that I replay only now
1. I call the next BeginConnect AFTER the first one EndConnect return , when
the other side doesn't return nothing , I will block on the EndConnect until
TimeOut occure.. it's take 20~ sec

2. Yes (I use socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);)
3. the BeginConnect make it
4. I want because when trying to make hole punch both peers need to send
async syn_sent (beginconnect) to the other in short period - this is the
reason I don't want to block for 20~ seconds on the EndConnect

I already solve it by call to socket.close and socket = null after 1+ sec if
the asyncresult did not signald
but still the hole punch does not work on this situation evenif I send a lot
of syn_sent...

Do you know what is hole punch ?
take a look in the article I sent before
also , if you have some link for free code that make hole punch in c# can be
great
thanks again

"Charles Wang[MSFT]" <ch******@online.microsoft.comwrote in message
news:zl**************@TK2MSFTNGXA01.phx.gbl...
>Hi,
I just discussed with Jeffery and we think that we have not totally
understood your issue. Te let us better understand your issue, could you
please answer me some questions?
1. What did you mean that you could call next BeginConnect after 20s?
2. Did all BeginConnect methods connect to the same endpoint?
3. How did you send the "syn_sent" to the endpoint if the connection had
not been established?
4. Why did you want to break the connection after 1s since it had not been
established? Wouldn't it also fail when the next BeginConnect was invoked?
5. Could you please mail me (ch******@microsoft.com) a sample project for
further research?

Sincerely yours,
Charles Wang
Microsoft Online Community Support

================================================= =====
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from this issue.
================================================= =====
This posting is provided "AS IS" with no warranties, and confers no rights.
================================================= =====



Nov 12 '06 #12
Hi,
I am afraid that the hole-pounch is not merely a programming technology
which also need the NAT to support on your router.
Hope this article may give you some reference:
Generic P2P Architecture, Tutorial and Example
http://www.codeproject.com/vbscript/...sp?df=100&foru
mid=35182&exp=0&select=767759
STUNT
http://nutss.gforge.cis.cornell.edu/stunt.php
Hope this helpful! Please feel free to let me know if you have any other
questions or concerns.

Charles Wang
Microsoft Online Community Support

Nov 13 '06 #13

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Edward Diener | last post: by
7 posts views Thread by Frank Maxey | last post: by
1 post views Thread by Nick Dodd via .NET 247 | last post: by
4 posts views Thread by John Allen | last post: by
2 posts views Thread by David | last post: by
reply views Thread by XIAOLAOHU | last post: by
reply views Thread by leo001 | last post: by
reply views Thread by Anwar ali | last post: by

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.