0

I've been considering what is optimal solution for implementing periodical (relatively long running) computations every x milliseconds in C# (.NET 4).

  1. Let say that x is 10000 (10 seconds).

    Probably the best solution in this case is DispatcherTimer which ticks every 10 seconds.
    In void timer_Tick(object sender, EventArgs e) function would be only code which starts Task (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.

  2. 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 for x? I mean: for some small x values it would be better to start one Task running for all the time until program does not exit. Inside created task there would be DispatcherTimer ticking every x 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 but Dispatcher Timer inside of the Task, ticking periodically every x (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;
    }
}
Community
  • 1
  • 1
patryk.beza
  • 4,876
  • 5
  • 37
  • 56
  • What are you trying to do? You have list of computations you need to perform (as a tasks)? Or every x seconds you want to kick off a computation as a task? – paparazzo Sep 16 '12 at 15:55
  • I think a timer makes more sense for a repeating task. I don't think the overhead of creating a Task would be all that great. But, if you *think* is might be: test and measure. If you don't know it *will* going into it, it probably isn't. – Peter Ritchie Sep 16 '12 at 17:01
  • In the case of timer, you're running something on the UI thread--which doesn't require any new threads to start. `Task` (with the default `TaskScheduler`) uses thread pool threads. The more thread pool threads you use, the more you stress the thread pool. Yes, that's what it's for, but that's a shared resource. e.g. if you have a long-running thread (i.e. longer than 1 second) the thread pool with start another thread to make sure it has a minimum number of available threads. – Peter Ritchie Sep 16 '12 at 17:04
  • @Blam - I'm trying to implement periodical checking (monitoring) connection with server. Normally it takes relatively much time to check out if there is connection with server. – patryk.beza Sep 16 '12 at 22:34
  • Then maybe update your update your question. Based on the wording I thought you meant a compute intensive operation. So you want to post an alert when a connection is down? What determines connection down - no answer to a ping? Post the code to test for connection up. – paparazzo Sep 16 '12 at 22:51

0 Answers0