用计时器替换代码而不是线程休眠

时间:2015-02-10 10:25:40

标签: c# multithreading timer

根据这个Stack Overflow discussion,使用Thread.Sleep()几乎总是一个坏主意。我将如何重构我的代码以使用计时器。我试着通过以下方式开始:

namespace Engine
{
    internal class Program
    {
        public static DbConnect DbObject = new DbConnect();

        System.Timers.Timer timer = new System.Timers.Timer();

        // error here
        timer.Interval = 2000;
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        timer.Enabled=false;
    }
}

但仍然收到cannot resolve symbol错误消息。

namespace Engine
{
    internal class Program
    {
    public static DbConnect DbObject = new DbConnect();
    private static void Main()
    {
        SettingsComponent.LoadSettings();

        while (true)
        {
            try
            {
                for (int x = 0; x < 4; x++)
                {
                    GenerateRandomBooking(); 
                }
                Thread.Sleep(2000); 
                GenerateRandomBids();
                AllocateBids();
                Thread.Sleep(2000); 
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
    }
}

2 个答案:

答案 0 :(得分:2)

如果您使用的是.Net 4.5或更高版本,则可以使用await代替计时器。

例如:

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

namespace Demo
{
    public static class Program
    {
        private static void Main()
        {
            Console.WriteLine("Generating bids for 30 seconds...");

            using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
            {
                var task = GenerateBids(cancellationTokenSource.Token);

                // You can do other work here as required.

                task.Wait();
            }

            Console.WriteLine("\nTask finished.");
        }

        private static async Task GenerateBids(CancellationToken cancel)
        {
            while (!cancel.IsCancellationRequested)
            {
                Console.WriteLine("");

                try
                {
                    for (int x = 0; x < 4; x++)
                        GenerateRandomBooking();

                    await Task.Delay(2000);

                    if (cancel.IsCancellationRequested)
                        return;

                    GenerateRandomBids();
                    AllocateBids();

                    await Task.Delay(2000);
                }

                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }

        private static void AllocateBids()
        {
            Console.WriteLine("AllocateBids()");
        }

        private static void GenerateRandomBids()
        {
            Console.WriteLine("GenerateRandomBids()");
        }

        private static void GenerateRandomBooking()
        {
            Console.WriteLine("GenerateRandomBooking()");
        }
    }
}

答案 1 :(得分:1)

您可以在不使用Thread.Sleep()

的情况下将此代码转换为此代码
private static void Main()
    {
        SettingsComponent.LoadSettings();

        //while (true)
        {
            try
            {
                RaiseRandomBooking(null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }

    static void RaiseRandomBooking(object state)
    {
        for (int x = 0; x < 4; x++)
        {
            GenerateRandomBooking();
        }
        System.Threading.Timer tmr = new System.Threading.Timer(RaiseRandomBids, null, 0, 2000);
    }

    static void RaiseRandomBids(object state)
    {
        GenerateRandomBids();
        AllocateBids();
        System.Threading.Timer tmr = new System.Threading.Timer(RaiseRandomBooking, null, 0, 2000);
    }