How to make a C# client show a timeout message if the server hasn't responded in 10 seconds
I need to write a client and a server in C# and the client needs to send a request to the server and if the server hasn't answered in 10 seconds, show a timeout message. The client and the server are both in Console.
Now, my first question is, is the class System.Threading.Timer
the best way of doing that, or should I look into asynchronous calls of delegates (after reading up on them, because I don't even under开发者_高级运维stand what they are, I've just been suggested them) or any other method? Also, if I am to use the Timer class, I understand that the TimerCallback
which is the first arguement of the Timer class, for example
Timer timer = new Timer(tcb);
is the method that executes when the timer ticks, but what do I do when I don't need to execute any methods each time the timer ticks, but want to show a message after the timer is done counting, say, 10 seconds?
I have looked into many msdn.microsoft.com articles and forum posts on this, but most people want to execute a method on each timer tick, or use asynchronous calls, and it is all very confusing.
One approach would be to make an async request using WebRequest (or something similar) and specifying a timeout. It the request does not return in time, it should throw an exception which you can then handle by displaying your message.
Or, you could use a Timer, and in the Timer's callback method you could display your message. If you use this approach, when your call returns it would need to stop the Timer to prevent the message from displaying. The timer will only "tick" as often as you specify, and after the first "tick" you can stop the timer so it will not execute more than once.
How your client-server will communicate?
In most of the communication methods you can set a time-out to the client call.
I recommend you to use WCF to make the client-server communication.
精彩评论