Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use async and await in timer

My windows app's requirement are:

  1. Using HttpWebRequest get web request/response every 3 seconds in one thread.(total is about 10 threads for doing this web request/response.)

  2. Each thread use some global variables.

I want to use a System.Timers.Timer and async and await. But I don't know that is a best way for high performance. And then how to test them. I am a green in C#.

like image 756
user2724902 Avatar asked Mar 17 '14 08:03

user2724902


Video Answer


1 Answers

You could write a RepeatActionEvery() method as follows.

It's parameters are:

  • action - The action you want to repeat every so often.
  • interval - The delay interval between calling action().
  • cancellationToken - A token you use to cancel the loop.

Here's a compilable console application that demonstrates how you can call it. For an ASP application you would call it from an appropriate place.

Note that you need a way to cancel the loop, which is why I pass a CancellationToken to RepeatActionEvery(). In this sample, I use a cancellation source which automatically cancels after 8 seconds. You would probably have to provide a cancellation source for which some other code called .Cancel() at the appropriate time. See here for more details.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    sealed class Program
    {
        void run()
        {
            CancellationTokenSource cancellation = new CancellationTokenSource(
              TimeSpan.FromSeconds(8));
            Console.WriteLine("Starting action loop.");
            RepeatActionEvery(() => Console.WriteLine("Action"), 
              TimeSpan.FromSeconds(1), cancellation.Token).Wait();
            Console.WriteLine("Finished action loop.");
        }

        public static async Task RepeatActionEvery(Action action, 
          TimeSpan interval, CancellationToken cancellationToken)
        {
            while (true)
            {
                action();
                Task task = Task.Delay(interval, cancellationToken);

                try
                {
                    await task;
                }
                catch (TaskCanceledException)
                {
                    return;
                }
            }
        }

        static void Main(string[] args)
        {
            new Program().run();
        }
    }
}
like image 134
Matthew Watson Avatar answered Nov 03 '22 09:11

Matthew Watson