Stop blocking call with Thread
Hello everyone.
I will try to do simple to describe my problem:
I have a service in which I call a method through a thread in another class that does this:
Code:
serverThread = new Thread (HttpServer. StartListening);
public static void StartListening ()
(
while (run)
(
....
TcpClient client = server. AcceptTcpClient ();
....
)
)
The problem is that whatever happens I find myself with a blocking call because even though my run variable is a false call for was already done.
So I can not stop my thread, and I can not stop my proper service.
How to stop this thread when i call blocking ballast?
Re: Stop blocking call with Thread
Why shouldn't you normally use the Thread.stop() method? Well, it is deprecated as of JDK1.2 because it can potentially leave the system in an unsafe state. If a thread
had a lock on an object (within a synchronized block), it might not release the object lock, causing problems at a later time. Note that this problem can affect older JVM implementations as well, JDK1.02 and JDK1.1 are not immune.
So while you shouldn't use Thread.stop() unless absolutely necessary, it is an acceptable way to kill a thread if it becomes stalled and you really need to shut it down fast.
Re: Stop blocking call with Thread
Yes thank you I used it, I still have problems to correct because there is always that thing which stops Thread. Is it fine we directly kill the thread in between the process or will it affect on the remaining process.
Re: Stop blocking call with Thread
Hi
I have the same concern, and I do not think BeginAccept can solve the problem because in a loop listening there will always be a blockage in the socket.
I tried to reference my overall socket (which is more of a UdpClient in my case) to be accessible from the main thread to close, but it does not work properly ...In fact it works well, but the function of blocking reception goes wrong ... so it's not very clean, should intercept the error not only that plant
Re: Stop blocking call with Thread
I managed to ensure that they do not need to intercept the error and my service stops after finally perfectly Changes 2 3.
Here's how I did it to avoid the intercept:
I used just a boolean that as soon as I invoke my method OnStop of the service, it will call a method in my class my listener passing a boolean false, therefore if a little before listening to an incoming connection:
Code:
public static void DoAcceptTcpClientCallback (IAsyncResult ar)
(
if (run)
(
Tracer. Trace ( "Connection detected");
/ / Blocking call to accept requests
using (TcpClient client = ((TcpListener) ar. AsyncState). EndAcceptTcpClient (ar))
......
)
else
(
tcpClientConnected. Set ();
)
(
To stop doing your service as:
Code:
HTTPServer. Arret () / / method that passes a boolean false;
Dispose ();
Tracer. Trace ( "Canstop");
CanStop = true;
method stop:
Code:
public static void Stop ()
(
run = false;
tcpClientConnected. Set ();
listener. Stop ();
)
Tell me if you're successful!