0

If i have a client that is connected to a server and if the server crashes, how can i determine, form my client, if the connection is off ? the idea is that if in my client's while i await to read a line from my server ( String a = sr.ReadLine(); ) and while the client is waiting to recieve that line , the server crashes , how do i close that thread that contains my while ?

Many have told me that in that while(alive) { .. } I should just change the alive value to true , but if my program is currently awaiting for a line to read, it won't get to exit the while because it will be trapped at sr.ReadLine() .

I was thinking that if i can't send a line to the server i should just close the client thread with .abort() . Any Ideas ?

Alex
  • 10,329
  • 28
  • 89
  • 163

5 Answers5

2

Have a TimeOut parameter in ReadLine method which takes a TimeSpan value and times out after that interval if the response is not received..

public string ReadLine(TimeSpan timeout)
{
   // ..your logic.
)

For an example check these SO posts -

Implementing a timeout on a function returning a value

Implement C# Generic Timeout

Community
  • 1
  • 1
Unmesh Kondolikar
  • 9,136
  • 3
  • 33
  • 51
1

Is the server app your own, or something off the shelf?

If it's yours, send a "heart beat" every couple of seconds to let the clients know that the connection and service are still alive. (This is a bit more reliable than just seeing if the connection is closed since it may be possible for the connection to remain open while the server app is locked.)

3Dave
  • 27,808
  • 18
  • 83
  • 150
0

If the server crashes I imagine you will have more problems than just fixing a while loop. Your program may enter an unstable state for other reasons. State should not be overlooked. That being said, a nice "server timed out" message may suffice. You could take it a step further and ping, then give a slightly more advanced message "server appears to be down".

P.Brian.Mackey
  • 41,438
  • 63
  • 228
  • 337
0

That the server crashes has nothing to do with your clients. There are several external factors that can make the connection go down: The client is one of them, internet/lan problems is another one.

It doesn't matter why something fails, the server should handle it anyway. Servers going down will make your users scream ;)

Regarding multi threading, I suggest that you look at the BeginXXX/EndXXX asynchronous methods. They give you much more power and a more robust solution.

jgauffin
  • 97,689
  • 42
  • 231
  • 359
0

Try to avoid any strategy that relies on thread abort(). If you cannot avoid it, make sure you understand the idiom for that mechanism, which involves having a separate appdomain and catching ThreadAbortException

Brent Arias
  • 27,679
  • 38
  • 128
  • 221