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

时间:2014-03-09 20:07:37

标签: c# timer delegates refactoring

我有一个由丑陋的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();
                           };
                   };
            };
    }

2 个答案:

答案 0 :(得分:2)

使用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());

}

答案 1 :(得分:0)

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

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