C#每秒运行函数的最佳方式,计时器还是线程? [英] C# Best Way to run a function every second, Timer vs Thread?

查看:137
本文介绍了C#每秒运行函数的最佳方式,计时器还是线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently using a thread to run a function every second in a console application C# is a thread the best way to do it? As I have asked a lot of my friends and they have suggested using a timer not a thread for running something every second? If it is a better option to use a timer how would I go about running a function every second using a timer? I have looked around but I am really unsure if that applies to be and if its the right way of going about it in my own way. So can someone tell me the answer and how I can do it?

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

So what is the best way to run it every second? Before you answer let me just let you know that this is running every second for like 2 days... My current thread coding

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

推荐答案

我将使用

I'd use a System.Threading.Timer because it generally uses less resources than a devoted thread. Here's an example:

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

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

This is a good choice for a Console app. However, you must of course bear in mind that the callback is still being done on a separate thread from the main thread, so you must be careful about synchronising resources and variables shared between the callback and the main thread.

这篇关于C#每秒运行函数的最佳方式,计时器还是线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆