473,714 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Sock ets.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.T imer 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 4120
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**********@y ahoo.com> wrote in message
news:6c******** *************** ***@posting.goo gle.com...
I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sock ets.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.T imer 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**********@y ahoo.com> wrote in message
news:6c******** *************** ***@posting.goo gle.com...
I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sock ets.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.T imer 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.Sock ets.Socket... I've reviewed the apis and found
nothing.... I can do timeouts with async sockets (BeginSend,
BeginReceive) via the WaitHandle.Wait One method... Is that what you
were thinking of?
-r

"William Stacey" <st***********@ mvps.org> wrote in message news:<#7******* *******@TK2MSFT NGP10.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**********@y ahoo.com> wrote in message
news:6c******** *************** ***@posting.goo gle.com...
I have a program that launches multiple threads with a ThreadStart
method like the following (using System.Net.Sock ets.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.T imer 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(IPEnd Point localEP) : base(localEP)
{
}

public byte[] SendReceive(byt e[] 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(re f remoteEP);
return receive;
}

public bool ReuseAddress
{
get
{
object tmpO = this.Client.Get SocketOption(So cketOptionLevel .Socket,
SocketOptionNam e.ReuseAddress) ;
return Convert.ToBoole an(tmpO);
}
set
{
Socket s = this.Client;
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.ReuseAddress, Convert.ToInt32 (value));
}
}

public int ReceiveTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReceiveTimeou t);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.ReceiveTimeou t, value);
}
}

public int SendTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.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.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.SendTimeout, value);
}
}

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

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

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

public IPEndPoint RemoteIPEndPoin t
{
get
{
return (IPEndPoint)Soc ket.RemoteEndPo int;
}
}

public IPEndPoint LocalIPEndPoint
{
get
{
return (IPEndPoint)Soc ket.LocalEndPoi nt;
}
}

} //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******* *******@TK2MSFT NGP11.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(IPEnd Point localEP) : base(localEP)
{
}

public byte[] SendReceive(byt e[] 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(re f remoteEP);
return receive;
}

public bool ReuseAddress
{
get
{
object tmpO = this.Client.Get SocketOption(So cketOptionLevel .Socket,
SocketOptionNam e.ReuseAddress) ;
return Convert.ToBoole an(tmpO);
}
set
{
Socket s = this.Client;
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.ReuseAddress, Convert.ToInt32 (value));
}
}

public int ReceiveTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReceiveTimeou t);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.ReceiveTimeou t, value);
}
}

public int SendTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.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.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.SendTimeout, value);
}
}

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

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

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

public IPEndPoint RemoteIPEndPoin t
{
get
{
return (IPEndPoint)Soc ket.RemoteEndPo int;
}
}

public IPEndPoint LocalIPEndPoint
{
get
{
return (IPEndPoint)Soc ket.LocalEndPoi nt;
}
}

} //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**********@y ahoo.com> wrote in message
news:6c******** *************** ***@posting.goo gle.com...
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******* *******@TK2MSFT NGP11.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(IPEnd Point localEP) : base(localEP)
{
}

public byte[] SendReceive(byt e[] 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(re f remoteEP);
return receive;
}

public bool ReuseAddress
{
get
{
object tmpO = this.Client.Get SocketOption(So cketOptionLevel .Socket,
SocketOptionNam e.ReuseAddress) ;
return Convert.ToBoole an(tmpO);
}
set
{
Socket s = this.Client;
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.ReuseAddress, Convert.ToInt32 (value));
}
}

public int ReceiveTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReceiveTimeou t);
}
set
{
if ( value < 0 )
value = 0;
Socket s = this.Client;
s.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.ReceiveTimeou t, value);
}
}

public int SendTimeout
{
get
{
Socket s = this.Client;
return (int)s.GetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.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.SetSocketOpti on(SocketOption Level.Socket,
SocketOptionNam e.SendTimeout, value);
}
}

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

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

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

public IPEndPoint RemoteIPEndPoin t
{
get
{
return (IPEndPoint)Soc ket.RemoteEndPo int;
}
}

public IPEndPoint LocalIPEndPoint
{
get
{
return (IPEndPoint)Soc ket.LocalEndPoi nt;
}
}

} //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
12673
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 under the Compact Framework, which does not support Abort. Will Socket.Close cause the Receive method to finish, or is there a better way?
4
4937
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 terminate this thread by calling the "Abort" funcion. But the thread does not terminate and after the form is closed this thread keeps running at blocked state. Basically the application keeps running because this thread does not terminate while...
2
2724
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 both client/server side. My cached for further use. While bytesReceived > 0 byteBuffer = New Byte(1024) {} bytesReceived = handler.Receive(byteBuffer) If bytesReceived > 0 Then ReDim Preserve m_data(bytesTotalReceived + bytesReceived - 1)
11
1868
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 looks something like this(pseudo code): class WorkerClass { Thread _listenerThread; public WorkerClass() {
2
9233
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 never ends the debuger and i have to hit the "little square" to stop the app. If make a shortcut to the exe and run it that way, it stays in the Windows Task Manager and I have to kill the process. Has anyone else run into this / work around?
6
5474
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 that. This thread is also outputting strings in a RichTextBox and in some rare instances I get a System.NullReferenceException when I exit the GUI. It seems like the _Closed() Method calls Thread.Abort() and then continues closing down/disposing...
25
2992
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
2336
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 via SMTP. Since smtplib.SMTP uses blocking IO, it can block the whole interpreter. Sometimes the whole thing would stop working indefinitely. I'm now aware that Twisted offers a non-blocking SMTP class, but I didn't really want to make that a...
14
5931
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 connected. Any idea? Thanks.
0
8796
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
8704
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
9170
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
9071
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,...
1
6627
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
4462
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
4715
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2514
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2105
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.