how to use async and await in timer

后端 未结 1 1343
悲&欢浪女
悲&欢浪女 2020-12-17 02:53

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

相关标签:
1条回答
  • 2020-12-17 03:18

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题