I've been considering what is optimal solution for implementing periodical (relatively long running) computations every x milliseconds in C# (.NET 4).
Let say that
xis 10000 (10 seconds).Probably the best solution in this case is
DispatcherTimerwhich ticks every 10 seconds.
Invoid timer_Tick(object sender, EventArgs e)function would be only code which startsTask(lets assume it would take ~5 seconds to complete the long running task).timer_Tickwould exit immediately and the task would be busy computing something.What about
x<1000 (1 second)?Wouldn't be there the big performance overhead creating and starting
Taskevery 1 second?
If not what is the time limit forx? I mean: for some smallxvalues it would be better to start oneTaskrunning for all the time until program does not exit. Inside created task there would beDispatcherTimerticking everyxsecond calling relatively long running function (maybe not 5 seconds but <1 second now; but still relatively long).Here comes the technical problem: how can I start the
Taskwhich would be running forever (until program is running)? I need nothing butDispatcher Timerinside of theTask, ticking periodically everyx(xis small enough).
I tried this way:
CancellationTokenSource CancelTokSrc = new CancellationTokenSource();
CancellationToken tok = CancelTokSrc.Token;
ConnCheckTask = new Task(() => { MyTaskMethod(tok); }, tok, TaskCreationOptions.LongRunning);
void MyTaskMethod(CancellationToken CancToken)
{
MyTimer = new DispatcherTimer(); // MyTimer is declared outside this method
MyTimer.Interval = x;
MyTimer.Tick += new EventHandler(timer_Tick);
MyTimer.IsEnabled = true;
while (true) ; // otherwise task exits and `timer_Tick` will be executed in UI thread
}
-- Edit: --
By intensive calculating I meant checking if connection with specified server is up or down. I want to monitor connection in order to alert user when connection goes down.
Checking connection is implemented this way (thanks to Ragnar):
private bool CheckConnection(String URL)
{
try
{
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
request.Timeout = 15000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return response.StatusCode == HttpStatusCode.OK ? true : false;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
return false;
}
}