繁体   English   中英

可怕的嵌套计时器,我该如何重构?

[英]Awful nested timers, how do I refactor?

我有一个由丑陋的13个参数组成的方法,但是我无法弄清楚如何将它们变成适当的子方法并且仍然完全相同,在三次迭代后停止,使用正确的参数,用不同的方法关闭,有人会帮助我朝正确的方向发展吗?

//Three part animation
    public void SetPlayerAnimation(int location, int x1, int y1, TimeSpan duration1, string sprite1, int x2, int y2, TimeSpan duration2, string sprite2, int x3, int y3, TimeSpan duration3, string sprite3, string endsprite)
    {
        //Get the sprite object to be animated
        TranslateTarget = "Sprite" + location.ToString();
        OnPropertyChanged("TranslateTarget");

        //Start first part
        RunAnimation(location, x1, y1, duration1, sprite1);

        var timer = new DispatcherTimer();
        timer.Interval = duration1;
        timer.Start();
        timer.Tick += (s, args) =>
            {
                //Start second part
                RunAnimation(location, x2, y2, duration2, sprite2);

                timer.Stop();

                var timer2 = new DispatcherTimer();
                timer2.Interval = duration2;
                timer2.Start();
                timer2.Tick += (s2, args2) =>
                   {
                       //Start third part
                       RunAnimation(location, x3, y3, duration3, sprite3);
                       timer2.Stop();

                       var timer3 = new DispatcherTimer();
                       timer3.Interval = duration2;
                       timer3.Start();
                       timer3.Tick += (s3, args3) =>
                           {
                               //End with a final sprite
                               SetPlayerSprite(location, endsprite);
                               timer3.Stop();
                           };
                   };
            };
    }

使用async / await,你所有的麻烦都消失了!

public void SetPlayerAnimation(int location, int x1, int y1, TimeSpan duration1, string sprite1, int x2, int y2, TimeSpan duration2, string sprite2, int x3, int y3, TimeSpan duration3, string sprite3, string endsprite)
{
    //Get the sprite object to be animated
    TranslateTarget = "Sprite" + location.ToString();
    OnPropertyChanged("TranslateTarget");
    Task.Factory.StartNew(
        async () => {
            RunAnimation(location, x1, y1, duration1, sprite1);
            await Task.Delay(duration1);
            RunAnimation(location, x2, y2, duration2, sprite2);
            await Task.Delay(duration2);
            RunAnimation(location, x3, y3, duration3, sprite3);
            await Task.Delay(duration2);
            SetPlayerSprite(location, endsprite);

        }, // this will use current synchronization context
        CancellationToken.None, 
        TaskCreationOptions.None, 
        TaskScheduler.FromCurrentSynchronizationContext());

}

你问了一个方向......正确方向的一步是:

  • 用真实方法替换所有匿名方法(代码少于curent方法)
  • 通过将所有以数字结尾的参数放在一个类中来减少参数

暂无
暂无

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

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