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
x
is 10000 (10 seconds).Probably the best solution in this case is
DispatcherTimer
which 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_Tick
would 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
Task
every 1 second?
If not what is the time limit forx
? I mean: for some smallx
values it would be better to start oneTask
running for all the time until program does not exit. Inside created task there would beDispatcherTimer
ticking everyx
second 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
Task
which would be running forever (until program is running)? I need nothing butDispatcher Timer
inside of theTask
, ticking periodically everyx
(x
is 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;
}
}