473,386 Members | 1,609 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Ending/restarting blocked C# thread using blocking Socket calls

I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sockets.Socket for UDP
packet transfers to a server):

ThreadStart pseudo code:

Connect
Receive response
Send Connect ACK

Send request for wml page
Receive wml page

Disconnect
Because I am using the blocking Socket calls to connect, send and
receive it is possible for the thread to get stuck in a blocked state.

I would like to be able to figure out when the thread is in the
blocked state and somehow stop/kill and then restart the thread again.

I tried using a System.Timers.Timer to wait on each blocking call… If
the timer interval expired then the Timer Elapsed event would be fired
and I could send an event back to the creator of the thread to kill
and restart the thread (killing via the Thread.Abort method).

However this has created multiple problems (specifically threads never
end up finishing, seemingly getting stuck in an endless loop).

So my question… Is there a way to accomplish this? Can someone
provide a basic outline or a hint at what methodologies I'm missing?

Many thanks in advance,
roger beniot
Nov 15 '05 #1
6 4075
Hi Roger,

I am not sure about sockets (have relatively little experience with them),
but with many other types of blocking, you can obtain a waitable handle that
can be passed to functions like WaitAll or WaitAny. You should use WaitAny
and wait for two handles - one for the blocking call and one for the
cancellation event. So, if you need to abort a thread, the thread creator
raises the cancellation event, the WaitAny call returns reporting that the
cancellation event object has been signaled and the thread gracefully exits.

Unfortunately, this way is not always available, so Thread.Abort may be your
only one option.

--
Dmitriy Lapshin [C# / .NET MVP]
X-Unity Test Studio
http://x-unity.miik.com.ua/teststudio.aspx
Bring the power of unit testing to VS .NET IDE

"roger beniot" <ro**********@yahoo.com> wrote in message
news:6c**************************@posting.google.c om...
I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sockets.Socket for UDP
packet transfers to a server):

ThreadStart pseudo code:

Connect
Receive response
Send Connect ACK

Send request for wml page
Receive wml page

Disconnect
Because I am using the blocking Socket calls to connect, send and
receive it is possible for the thread to get stuck in a blocked state.

I would like to be able to figure out when the thread is in the
blocked state and somehow stop/kill and then restart the thread again.

I tried using a System.Timers.Timer to wait on each blocking call… If
the timer interval expired then the Timer Elapsed event would be fired
and I could send an event back to the creator of the thread to kill
and restart the thread (killing via the Thread.Abort method).

However this has created multiple problems (specifically threads never
end up finishing, seemingly getting stuck in an endless loop).

So my question… Is there a way to accomplish this? Can someone
provide a basic outline or a hint at what methodologies I'm missing?

Many thanks in advance,
roger beniot


Nov 15 '05 #2
Does setting the send and receive timeouts not work for you? You can catch
those exceptions and move on.

--
William Stacey, MVP

"roger beniot" <ro**********@yahoo.com> wrote in message
news:6c**************************@posting.google.c om...
I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sockets.Socket for UDP
packet transfers to a server):

ThreadStart pseudo code:

Connect
Receive response
Send Connect ACK

Send request for wml page
Receive wml page

Disconnect
Because I am using the blocking Socket calls to connect, send and
receive it is possible for the thread to get stuck in a blocked state.

I would like to be able to figure out when the thread is in the
blocked state and somehow stop/kill and then restart the thread again.

I tried using a System.Timers.Timer to wait on each blocking call. If
the timer interval expired then the Timer Elapsed event would be fired
and I could send an event back to the creator of the thread to kill
and restart the thread (killing via the Thread.Abort method).

However this has created multiple problems (specifically threads never
end up finishing, seemingly getting stuck in an endless loop).

So my question. Is there a way to accomplish this? Can someone
provide a basic outline or a hint at what methodologies I'm missing?

Many thanks in advance,
roger beniot

Nov 15 '05 #3
I'm not familar with how you set a timeout for a
System.Net.Sockets.Socket... I've reviewed the apis and found
nothing.... I can do timeouts with async sockets (BeginSend,
BeginReceive) via the WaitHandle.WaitOne method... Is that what you
were thinking of?
-r

"William Stacey" <st***********@mvps.org> wrote in message news:<#7**************@TK2MSFTNGP10.phx.gbl>...
Does setting the send and receive timeouts not work for you? You can catch
those exceptions and move on.

--
William Stacey, MVP

"roger beniot" <ro**********@yahoo.com> wrote in message
news:6c**************************@posting.google.c om...
I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sockets.Socket for UDP
packet transfers to a server):

ThreadStart pseudo code:

Connect
Receive response
Send Connect ACK

Send request for wml page
Receive wml page

Disconnect
Because I am using the blocking Socket calls to connect, send and
receive it is possible for the thread to get stuck in a blocked state.

I would like to be able to figure out when the thread is in the
blocked state and somehow stop/kill and then restart the thread again.

I tried using a System.Timers.Timer to wait on each blocking call. If
the timer interval expired then the Timer Elapsed event would be fired
and I could send an event back to the creator of the thread to kill
and restart the thread (killing via the Thread.Abort method).

However this has created multiple problems (specifically threads never
end up finishing, seemingly getting stuck in an endless loop).

So my question. Is there a way to accomplish this? Can someone
provide a basic outline or a hint at what methodologies I'm missing?

Many thanks in advance,
roger beniot

Nov 15 '05 #4
If using tcpclient class, the send and receive timeouts are members you set.
If using UdpClient, you need to inherit from UdpClient to get access to the
socket to get access to the send/receive timeouts. Here is an example:
public class UDPClient : UdpClient
{
public UDPClient() : base()
{
}

public UDPClient(int port) : base(port)
{
}

public UDPClient(IPEndPoint localEP) : base(localEP)
{
}

public byte[] SendReceive(byte[] dgram, IPEndPoint destEP, ref IPEndPoint
remoteEP)
{
if ( dgram == null || destEP == null )
return null;

byte[] receive;

this.Send(dgram, dgram.Length, destEP); //Send using base's Send();
receive = this.Receive(ref remoteEP);
return receive;
}

public bool ReuseAddress
{
get
{
object tmpO = this.Client.GetSocketOption(SocketOptionLevel.Sock et,
SocketOptionName.ReuseAddress);
return Convert.ToBoolean(tmpO);
}
set
{
Socket s = this.Client;
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, Convert.ToInt32(value));
}
}

public int ReceiveTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, value);
}
}

public int SendTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
//Uses the Socket returned by Client to set an option that is not
available using UdpClient.
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, value);
}
}

public Socket Socket
{
get { return this.Client; }
set
{
if ( value == null )
throw new ArgumentNullException("Socket", "Socket is null.");
this.Client = value;
}
}

public bool Connected
{
get
{
return Socket.Connected;
}
}

public bool IsActive
{
get { return this.Active; }
}

public IPEndPoint RemoteIPEndPoint
{
get
{
return (IPEndPoint)Socket.RemoteEndPoint;
}
}

public IPEndPoint LocalIPEndPoint
{
get
{
return (IPEndPoint)Socket.LocalEndPoint;
}
}

} //End UDPClient Class

--
William Stacey, MVP
Nov 15 '05 #5
Wow... William thank you very much... The option to set the
ReceiveTimeout is something I was unable to find (and would have never
dug that deep to find it).

I had already tried inheriting the UdpClient and Socket classes to
build in this functionality, but this is much easier...

The one thing that seems missing is what happens when the timeout
occurs?? Does it just give up on the call (say the Receive call) and
drop through to the rest of the code... or is there a way to "catch"
an event/exception/etc that can tell you the timeout occured?
I've already switched over to async sockets, but I'm interested in the
synch solution as well..

Many thanks again!
-r
"William Stacey" <st***********@mvps.org> wrote in message news:<#P**************@TK2MSFTNGP11.phx.gbl>...
If using tcpclient class, the send and receive timeouts are members you set.
If using UdpClient, you need to inherit from UdpClient to get access to the
socket to get access to the send/receive timeouts. Here is an example:
public class UDPClient : UdpClient
{
public UDPClient() : base()
{
}

public UDPClient(int port) : base(port)
{
}

public UDPClient(IPEndPoint localEP) : base(localEP)
{
}

public byte[] SendReceive(byte[] dgram, IPEndPoint destEP, ref IPEndPoint
remoteEP)
{
if ( dgram == null || destEP == null )
return null;

byte[] receive;

this.Send(dgram, dgram.Length, destEP); //Send using base's Send();
receive = this.Receive(ref remoteEP);
return receive;
}

public bool ReuseAddress
{
get
{
object tmpO = this.Client.GetSocketOption(SocketOptionLevel.Sock et,
SocketOptionName.ReuseAddress);
return Convert.ToBoolean(tmpO);
}
set
{
Socket s = this.Client;
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, Convert.ToInt32(value));
}
}

public int ReceiveTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, value);
}
}

public int SendTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
//Uses the Socket returned by Client to set an option that is not
available using UdpClient.
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, value);
}
}

public Socket Socket
{
get { return this.Client; }
set
{
if ( value == null )
throw new ArgumentNullException("Socket", "Socket is null.");
this.Client = value;
}
}

public bool Connected
{
get
{
return Socket.Connected;
}
}

public bool IsActive
{
get { return this.Active; }
}

public IPEndPoint RemoteIPEndPoint
{
get
{
return (IPEndPoint)Socket.RemoteEndPoint;
}
}

public IPEndPoint LocalIPEndPoint
{
get
{
return (IPEndPoint)Socket.LocalEndPoint;
}
}

} //End UDPClient Class

Nov 15 '05 #6
Yes. A SocketException exception will be thrown. You can just catch this
in your code that calls this method, you don't have to catch it and rethrow
it inside the udpclient wrapper as that would just be redundant IMO. You
can check use SocketException.ErrorCode to obtain the specific error code.
hth As far as async/sync goes. I am tending to like sending on one thread
and receiving on another (sharing the same socket) over using async as I
find it more nature to code and I think more efficient - but a lot of folks
use async.

--
William Stacey, MVP

"roger beniot" <ro**********@yahoo.com> wrote in message
news:6c**************************@posting.google.c om...
Wow... William thank you very much... The option to set the
ReceiveTimeout is something I was unable to find (and would have never
dug that deep to find it).

I had already tried inheriting the UdpClient and Socket classes to
build in this functionality, but this is much easier...

The one thing that seems missing is what happens when the timeout
occurs?? Does it just give up on the call (say the Receive call) and
drop through to the rest of the code... or is there a way to "catch"
an event/exception/etc that can tell you the timeout occured?
I've already switched over to async sockets, but I'm interested in the
synch solution as well..

Many thanks again!
-r
"William Stacey" <st***********@mvps.org> wrote in message

news:<#P**************@TK2MSFTNGP11.phx.gbl>...
If using tcpclient class, the send and receive timeouts are members you set. If using UdpClient, you need to inherit from UdpClient to get access to the socket to get access to the send/receive timeouts. Here is an example:
public class UDPClient : UdpClient
{
public UDPClient() : base()
{
}

public UDPClient(int port) : base(port)
{
}

public UDPClient(IPEndPoint localEP) : base(localEP)
{
}

public byte[] SendReceive(byte[] dgram, IPEndPoint destEP, ref IPEndPoint remoteEP)
{
if ( dgram == null || destEP == null )
return null;

byte[] receive;

this.Send(dgram, dgram.Length, destEP); //Send using base's Send();
receive = this.Receive(ref remoteEP);
return receive;
}

public bool ReuseAddress
{
get
{
object tmpO = this.Client.GetSocketOption(SocketOptionLevel.Sock et,
SocketOptionName.ReuseAddress);
return Convert.ToBoolean(tmpO);
}
set
{
Socket s = this.Client;
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, Convert.ToInt32(value));
}
}

public int ReceiveTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, value);
}
}

public int SendTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
//Uses the Socket returned by Client to set an option that is not
available using UdpClient.
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, value);
}
}

public Socket Socket
{
get { return this.Client; }
set
{
if ( value == null )
throw new ArgumentNullException("Socket", "Socket is null.");
this.Client = value;
}
}

public bool Connected
{
get
{
return Socket.Connected;
}
}

public bool IsActive
{
get { return this.Active; }
}

public IPEndPoint RemoteIPEndPoint
{
get
{
return (IPEndPoint)Socket.RemoteEndPoint;
}
}

public IPEndPoint LocalIPEndPoint
{
get
{
return (IPEndPoint)Socket.LocalEndPoint;
}
}

} //End UDPClient Class

Nov 15 '05 #7

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

Similar topics

2
by: Bruce Vander Werf | last post by:
How can I cleanly stop a thread that is currently blocking on Socket.Receive? I don't want to use Thread.Abort, because I would like the thread method to exit cleanly, and the same code must run...
4
by: Dr. J | last post by:
How to terminate a blocked thread? In my form's "load" I launch a TCP listening thread that stays in an infinite loop waiting for incoming TCP packets. In this form's "closing" I try to...
2
by: Qindong Zhang | last post by:
My socket application blocked at socket.receiver() after received all information from sender. Should socket.Receive() return 0 after no more data available? Note: My socket object was not close on...
11
by: Steve | last post by:
I'm having a problem with my Thread usage and I think the general design of how I'm working with them. My UI class calls a method in another class that does a lot of work. That "worker" class...
2
by: Miro | last post by:
VB 2003. I cant find the last thing im missing. I click the "Run" button to run my app in VB.net and it runs. But when i close the application, the thread does not end ( i think ) because it...
6
by: Joe HM | last post by:
Hello - I have a function that calls Thread.Abort() to stop a thread in a _Closed() Method of a GUI. The thread contains a blocking call on a TCP socket and that is the easiest way to stop...
25
by: JC | last post by:
Hi People, Please I need your help. This code run a thread ok but Not close later. thanks... private void RunServer(int aPortNumber) {
5
by: Gordon Messmer | last post by:
I believe that I've seen this discussed previously, so maybe there's some interest in it. I wrote a threaded mail filtering framework a while ago, and one of the modules does address verification...
14
by: =?Utf-8?B?TWlrZVo=?= | last post by:
I have a sync socket application. The client is blocked with Socket.Receive(...) in a thread, another thread calls Socket.Close(). This unblock the blocked thread. But the socket server is still...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...

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.