gpt4 book ai didi

C#每秒运行一个函数的最佳方式,定时器与线程?

转载 作者:太空狗 更新时间:2023-10-29 22:09:10 26 4
gpt4 key购买 nike

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

那么每秒运行一次的最佳方式是什么?在你回答之前,让我告诉你,它每秒都在运行大约 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);
}
}
}

这是控制台应用程序的不错选择。但是,您当然必须牢记,回调仍然是在与主线程不同的线程上完成的,因此您必须小心同步回调和主线程之间共享的资源和变量。

关于C#每秒运行一个函数的最佳方式,定时器与线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28545489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com