I am having some business logic to check a webservice whether it is alive or not.
I want to check it repeatedly after every 5 minutes for 1 hour after the starting time.
How to do this through either tasks or threads or await/async functionality.
I am having some business logic to check a webservice whether it is alive or not.
I want to check it repeatedly after every 5 minutes for 1 hour after the starting time.
How to do this through either tasks or threads or await/async functionality.
a thread solution looks like this:
public class WebserviceChecker {
private int durationInHours = 1;
public void setDuration(int value) { durationInHours = value; }
private boolean _shutdown = false;
private DateTime _startTime = null;
// System.Windows.Forms.Timer
private Timer _timer = null;
public void CheckWebservice() {
_startTime = DateTime.Now;
_timer = new Timer();
_timer.Tick += handleTimerTick;
while(!_shutdown) {
try {
// do what ever you want to do for checking your webservice...
// ...
} catch (ThreadAbortedException ex) {
// do cleanup, then
//
break;
} catch (Exception ex) {
Logger.Instance.log(LoggerLogType.Type.Err, ex.ToString());
}
// wait 5 secs (customize to your needs)
Threading.Thread.Sleep(5000);
}
if(_shutdown) {
// do some regular cleanup here...
}
} // public void CheckWebservice()
public void Shutdown() {
_shutdown = true;
}
private void handleTimerTick(Object sender, System.EventArgs e) {
TimeSpan ts = _startTime .Subtract(DateTime.Now);
if(ts.TotalHours >= durationInHours) {
Shutdown();
}
}
}
and now start the background thread like this:
WebserviceChecker _c = new WebserviceChecker();
Thread _watcher = new Thread(_c.CheckWebservice);
_watcher.IsBackground = true;
_watcher.Start();
for a scheduled task look here: C# start a scheduled task
i would prefer the thread solution because getting data from an external process is a little bit more complicated. synchronizing thread data into your main thread is easier. you would need paradigms like IPC (Inter Process Communication) over WCF by named pipes or socket communication (TCP/UDP).
if you need a hint how to get data back from your thread: you could e.g. define an event in the WebserviceChecker class which you will rise when there is a state change of your WS.
some words about the IsBackground thing... if you DONT set a thread to background, your application will only exit, when every foreground thread has exited his worker method. Background Threads will automatically aborted, when the application shuts down.
a word to the ThreadAbortedException: in .NET we gain the privileg to hard abort a thread. the framework will rise this exception at any position in the thread method to exit it. if you don't catch it, the thread will exit without cleanup. so just catch it, and clean up memory or do some finishing tasks. you would do this here like that:
_watcher.Abort();
cheers ceth :)
[edit] there's a good multi threading tutorial at MSDN: http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx [/edit]
[edit] if you want to use System.Threading.Timer you need to implement the System.Threading.TimerCallback delegate into your watcher class. then you can instantiate a new timer with a period instead of the background thread. see http://msdn.microsoft.com/de-de/library/system.threading.timercallback.aspx for more details [/edit]
First, re-examine your business requirements. What exactly does this get you? A webservice may suddenly go away at any time, so the fact that you just checked it doesn't mean that your next call will succeed. This is true for all network communications.
So the complexity of your "real" code is not reduced if you have a separate "checker". The only benefit of this kind of design is some kind of visual notification to a user that they can be reasonably sure their next call to the service will succeed. Even then you may want to reconsider, because it's only reasonably sure, and users will get mad if you lie to them.
That said, you can do it using Task
s like this:
private static async Task CheckAsync(CancellationToken token)
{
// Check your web service.
await CheckWebServiceAsync(token);
// Wait 5 minutes.
await Task.Delay(TimeSpan.FromMinutes(5), token);
}
...
var done = new CancellationTokenSource(TimeSpan.FromHours(1));
Task checkingTask = CheckAsync(done.Token);
// When checkingTask completes:
// IsCanceled -> One hour passed with no errors.
// IsFaulted -> The web service failed.