繁体   English   中英

C#每秒运行函数的最佳方法,计时器还是线程?

[英]C# Best Way to run a function every second, Timer vs Thread?

我目前正在使用线程在控制台应用程序中每秒运行一个函数,C#是执行此操作的最佳方法吗? 正如我问过很多朋友的建议,他们建议使用计时器,而不是每秒钟运行某个线程的线程? 如果使用计时器是更好的选择,我将如何使用计时器每秒运行一个函数? 我环顾四周,但我真的不确定这是否适用,以及按照我自己的方式正确解决问题的方法。 有人可以告诉我答案以及我该怎么做吗?

那么,每秒运行它的最佳方法是什么? 在回答之前,请让我知道它每秒运行大约2天...我当前的线程编码

namespace Reality.Game.Misc
{
    using Reality;
    using Reality.Communication.Outgoing;
    using Reality.Game.Rooms;
    using Reality.Game.Sessions;
    using Reality.Storage;
    using System;
    using System.Data;
    using System.Threading;

    public static class JobCacheWorker
    {
        private static Thread jWorkerThread;

        public static void HandleExpiration(Session Session)
        {
             using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
            {
                Session.CharacterInfo.UpdateWorking(client, 0);
            }
        }

        public static void Initialize()
        {
            jWorkerThread = new Thread(new ThreadStart(JobCacheWorker.ProcessThread));
            jWorkerThread.Priority = ThreadPriority.Highest;
            jWorkerThread.Name = "JobCacheWorker";
            jWorkerThread.Start();
        }

        public static void CheckEffectExpiry(Session Session)
        {
            try
            {
                //RunMyCodeHere...
            }
            catch (Exception exception)
            {
                    Console.WriteLine("Exception - JobCacheWorker -> " + exception.Message);
            } 
        }

        private static void ProcessThread()
        {
            while (Program.Alive)
            {
                try
                {
                    foreach (Session Session in SessionManager.Sessions.Values)
                    {
                        if (Session != null && Session.Authenticated && !Session.Stopped)
                        {
                            CheckEffectExpiry(Session);
                            Thread.Sleep(1000);
                        }
                    }
                }
                catch (ThreadAbortException exception)
                {
                    Output.WriteLine("ThreadAbortException - JobCacheWorker -> " + exception.Message);
                }
                catch (ThreadInterruptedException exception2)
                {
                    Output.WriteLine("ThreadInterruptedException - JobCacheWorker -> " + exception2.Message);
                }
            }
         }
    }
}

我将使用System.Threading.Timer因为它通常比专用线程使用更少的资源。 这是一个例子:

using System;
using System.Threading;

namespace Demo
{
    public static class Program
    {
        public static void Main()
        {
            Console.WriteLine("Starting timer with callback every 1 second.");

            Timer timer = new Timer(callback, "Some state", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

            Thread.Sleep(4500); // Wait a bit over 4 seconds.

            Console.WriteLine("Changing timer to callback every 2 seconds.");

            timer.Change(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));

            Thread.Sleep(9000);

            timer.Change(-1, -1); // Stop the timer from running.

            Console.WriteLine("Done. Press ENTER");

            Console.ReadLine();
        }

        private static void callback(object state)
        {
            Console.WriteLine("Called back with state = " + state);
        }
    }
}

对于控制台应用程序,这是一个不错的选择。 但是,您必须牢记,回调仍在与主线程分离的线程上进行,因此您必须小心同步在回调和主线程之间共享的资源和变量。

您可以看一下System.Threading.Timer ,它定期在线程池上执行一个回调,这使它比线程更准确。 这里的代码看起来像

static void Main(string[] args)
{
    TimerCallback tmCallback = CheckEffectExpiry; 
    Timer timer =  new Timer(tmCallback,"test",1000,1000);
    Console.WriteLine("Press any key to exit the sample");
    Console.ReadLine(); 
}

static  void CheckEffectExpiry(object objectInfo)
{
    //TODO put your code
}

如果您希望任务与任何当前任务并行运行,那么使用线程不是一个坏选择。 尽管由于该任务每秒都会发生,但我认为这是一个非常小的任务。 在这种情况下,最好使用计时器,因为这样可以减少代码并更易于理解。

为此,您可以引用系统计时器类。 它有一个例子,应有尽有。
但总的来说,这些是您要做的事情:

  1. 创建一个计时器实例(最好是全局声明并在Initialize()中对其进行初始化)
  2. 设置时间间隔(1秒= 1000毫秒)
  3. 启用计时器
  4. 启动它
  5. (可选)您甚至可以将其停止

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM