C# - 如何阻止GUI或事件

时间:2009-10-03 00:37:17

标签: c# wpf user-interface synchronization blocking

我正在尝试使用WPF创建一个非常简单的游戏Simon和WiiMote版本。我坚持的是如何使它基于回合,程序阻塞,直到GUI完成显示序列。

这是我到目前为止的代码(主要基于这里的答案:WPF - sequential animation simple example):

public partial class Window1 : Window
{

    public enum SimonSquare { BLUE = 1, GREEN = 3, RED = 5, YELLOW = 7 };

    List<int> _correctSequence;
    int _currentLevel = 1;
    Random random = new Random();
    Wiimote _wiiMote;
    List<int> _squaresEntered;
    private IEnumerator<Action> _actions;
    Rectangle blueRect;
    Rectangle redRect;
    Rectangle greenRect;
    Rectangle yellowRect;

    AutoResetEvent autoEvent;

    public Window1()
    { 
        InitializeComponent(); 
        blueRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Blue, Name = "Blue"};
        redRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Red, Name = "Red" }; 
        greenRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Green, Name = "Green" };
        yellowRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Yellow, Name = "Yellow" };

        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(blueRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(redRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(greenRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(yellowRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        //connectWiiRemote();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _actions = AnimationSequence().GetEnumerator();
        autoEvent = new AutoResetEvent(false);
        Thread thread = new Thread(RunNextAction);
        thread.Start();
        autoEvent.WaitOne(); // need to block here somehow!
        int x = 5;
    }   

    IEnumerable<Action> AnimationSequence() 
    {
        getSequence();
        foreach(int square in _correctSequence)
        {
            if(square == (int) SimonSquare.BLUE)
                yield return () => animateCell(blueRect, Colors.Blue); 
            else if(square == (int) SimonSquare.RED)
                yield return () => animateCell(redRect, Colors.Red);
            else if (square == (int)SimonSquare.GREEN)
                yield return () => animateCell(greenRect, Colors.Green);
            else if (square == (int)SimonSquare.YELLOW)
                yield return () => animateCell(yellowRect, Colors.Yellow);
        }
    }

    private void animateCell(Rectangle rectangle, Color fromColor)
    {
        this.Dispatcher.BeginInvoke(new Action(delegate
        {
            Color toColor = Colors.White;
            ColorAnimation ani = new ColorAnimation(toColor, 
                new Duration(TimeSpan.FromMilliseconds(300)));
            ani.AutoReverse = true;
            SolidColorBrush newBrush = new SolidColorBrush(fromColor);
            ani.BeginTime = TimeSpan.FromSeconds(2);
            rectangle.Fill = newBrush;
            ani.Completed += (s, e) => RunNextAction();
            newBrush.BeginAnimation(SolidColorBrush.ColorProperty, ani);

        }));
    }

    private void RunNextAction()
    {
        if (_actions.MoveNext())
            _actions.Current();
        else
        {
            autoEvent.Set();
            _currentLevel++;
        }
    }

    private void getSequence()
    {
        _correctSequence = new List<int>();
        int[] values = 
            Enum.GetValues(typeof(SimonSquare)).Cast<int>().ToArray();
        for (int i = 0; i < _currentLevel + 2; i++)
        {
            _correctSequence.Add(values[random.Next(values.Length)]);
        }

    }
}

但是,autoSet的waitOne / set无法正常工作。它当前调用RunNextAction一次,但随后无限期地阻塞waitOne。我做错了什么?

编辑: 让我试着改写一下这个问题。如果我拿出Threading和AutoResetEvent,在Window_Loaded中我有:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _actions = AnimationSequence().GetEnumerator();
        RunNextAction(); // shows all of the flashing squares
        // need to wait here until the flashing squares are all shown
        // process player's events etc.
    }

当我运行上面的代码时,它会调用RunNextAction一次,它会一直调用自己直到显示所有的方块(看起来像是在它自己的线程上),但WindowLoaded方法仍在继续。在我调用RunNextAction()之后,我需要阻止Window_Loaded,直到RunNextAction完全完成。

4 个答案:

答案 0 :(得分:1)

你不应该在Dispatcher Thread上调用WaitOne !!

你在Dispatcher Thread本身上调用WaitOne,调度程序线程是WPF APP的主线程,如果你阻塞它,任何对Dispatcher.BeginInvoke或Invoke的调用将永远不会被调用,它将无限期地等待。

相反,更好的方法是将动画移动到另一个名为“AnimationDialog”的窗口并将其加载为模态对话框。

private void window_loaded(object sender, EventArgs e){

    AnimationDialog dialog = new AnimationDialog();
    dialog.Owner = this;
    dialog.ShowDialog(); // this will wait here 

}

在AnimationDialog窗口中......

private void Window_Loaded(object sender, EventArgs e){
    StartAnimationThread();
    // dont do any wait or block here at all...
}

// in your end of animation call "EndAnimation()"

private void EndAnimation(){
    Dispatcher.BeginInvoke()((Action)delegate(){
        this.DialogResult = true; 
        // this will stop this dialog and
        // and execute the parent window's
        // code where showdialog was called... 
    }
    )
}

答案 1 :(得分:0)

我可能误解了你的问题,因为这似乎很简单。在Window_Loaded事件中,删除thread.Start();之后的所有内容。添加名为_ImDoneSimonizing的类级变量,并将其初始化为false。对于接收用户输入的任何方法,请将其包装在代码中:

if (_ImDoneSimonizing)
{
    // do whatever
}

动画完成后,将_ImDoneSimonizing设为true

另外两点:

  1. 非常酷,你带回西蒙。自Twister以来的最佳游戏。
  2. 您可以使用WPF为Wii创建游戏吗?先生,你震撼了我的世界。

答案 2 :(得分:0)

AutoResetEvent正在执行它的设计,阻止线程执行直到调用Set()。这可能只是意味着你没有调用Set()。也许你的迭代器没有按照你期望的方式工作(尽管没有测试它看起来没问题)。

你是否在其他地方调用Window_Loaded?

答案 3 :(得分:0)

您可以通过抽取Windows消息队列来解决此问题。基本上,如果您将回调发布到消息队列,则调用线程将阻塞,直到呈现完成。这是一篇解释如何操作的文章:http://graemehill.ca/wpf-rendering-thread-synchronization