Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - 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#.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...