使用仅在回调执行到结束时才继续的定时器

时间:2014-07-10 21:03:31

标签: c#

我正在开发游戏服务器,我需要处理一些事件。例如:玩家想要攻击其他玩家。如果可以的话,每秒执行一次事件就会造成伤害。

有一个示例代码不能正常工作,但我希望你能得到这个想法!

using System.Timers;
public class Test
{
    public static Timer FightTimer;
    // Session is the player
    public static void Main(Session Session)
    {


        FightTimer = new Timer(1000); // one second interval

        // Hook up the Elapsed event for the timer.
        FightTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 1 seconds (2000 milliseconds).
        FightTimer.Interval = 1000;
        FightTimer.Enabled = true;
    }

    public static void Fight(object attacker)
    {
        FightTimer.stop();
        // get the session
        Session Session = (Session)attacker;

        if (Session.CharacterInfo.IsDestroy == true)
        {
            return;
        }

        // Ok here will be calculated all damage and ect...
        // if there's no others "return" for stopping the execution we can let the timer call
        // the callback again. if not, the timer is stopped and disposed

        FightTimer.start();
    }
}

嗯,我希望你有这个想法,我的问题是我根本不知道如何做到这一点,所以我希望你能够帮助我。提前谢谢!

1 个答案:

答案 0 :(得分:1)

由于您使用的是System.Timer class,因此可以使用System.Timer.Enabled property。将属性设置为false将停止计时器滴答 - 它将不再raise the Elapsed event

代码中需要更改的内容:

  • 将计时器变量设为全局(或将其传递给所需方法)
  • 然后使用FightTimer.Enabled = false;停止

修改后的代码(一种可能的解决方案):

using System.Timers;
public class Test
{
    // Session is the player
    static Timer FightTimer = null;

    public static void Main(Session Session)
    {
        FightTimer = new Timer(1000); // one second interval

        // Hook up the Elapsed event for the timer.
        FightTimer.Elapsed += new ElapsedEventHandler(Fight);

        // Set the Interval to 1 seconds
        FightTimer.Interval = 1000;
        FightTimer.Enabled = true;
    }

    public static void Fight(object attacker)
    {
        // get the session
        Session Session = (Session)attacker;

        if (Session.CharacterInfo.IsDestroy == true)
        {
            return;
        }

        // Ok here will be calculated all damage and ect...
        // if there's no others "return" for stopping the execution we can let the timer call
        // the callback again. if not, the timer is stopped and disposed
        FightTimer.Enabled = false;
        // modify to your needs
    }
}