【问题标题】:Wait for variable to change等待变量改变
【发布时间】:2015-06-21 14:36:30
【问题描述】:

我有一个方法可以显示一个窗口,然后返回单击的按钮的值。我所做的是,当我单击按钮时,我更改了一个变量,然后该变量将被返回。我需要以某种方式暂停该方法,直到变量被更改。

我用统一编程一个游戏,它使用单声道。

代码:

public virtual Buttons Execute(){

        this.holder.SetActive(true); //Set the window active

        // Here wait for the user to click a button

        return clicked;//Returns the button clicked.
    }

【问题讨论】:

  • 不清楚你的意思。当您设置变量的值时,它会立即更改。你需要等待什么?你能展示复制问题的代码并解释什么不起作用吗?
  • @David 问题是我需要知道你是如何暂停方法直到变量改变值,因为我不知道它会是几秒钟或几分钟直到发生这种情况..
  • @Olof:您不必“暂停代码”来等待事件发生。应该有其他代码在事件发生时响应事件。从您展示的代码中并不清楚在这种情况下应该如何发生这种情况,但您应该响应按钮单击而不是等待它。

标签: c# multithreading mono


【解决方案1】:

处理用户界面的代码是事件驱动的,所以明智的做法是使用事件,而不是像您尝试做的那样使用方法。

可能创建一个以这种方式工作的方法,但您必须创建自己的消息泵,在等待时运行:

public virtual Buttons Execute(){

    this.holder.SetActive(true); // Set the window active

    clicked = null; // Set the state as undetermined

    while (clicked == null) { // Wait until it is set

      Application.DoEvents(); // Process messages
      Thread.Sleep(10); // Wait for a while

    }

    return clicked; // Returns the button clicked.
}

您可以阅读问题Use of Application.DoEvents(),了解以这种方式使用DoEvents 的陷阱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 2018-07-01
    • 1970-01-01
    相关资源
    最近更新 更多