簡體   English   中英

C#如何在Thread.Sleep()之前執行代碼? [解決]

[英]C# how to execute code before Thread.Sleep()? [RESOLVED]

    void SpaceBarUpdate() {

        if (Input.GetKeyDown("space") && timerStart == 0)   //if the timer isn't initialized and spacebar pressed
        {
            //txt.color = Color.red;

            UnityEngine.Debug.Log("Sleep started");
            Thread.Sleep(550);
            UnityEngine.Debug.Log("Sleep ended");


            if (Input.GetKey("space"))
            {
                UnityEngine.Debug.Log("Space down");

                // txt.color = Color.green;
                txt.text = "READY";

                //timerStart = 1;
            }

        }
    }

如果按下空格鍵,此代碼的輸出將如下所示:(不帶顏色格式)

Sleep started
# delay of 550ms
Sleep ended

然后如果仍然按住空格鍵,

Space down

但是,一旦點擊空格鍵,它會在 550 毫秒內不輸出任何內容,然后立即輸出:(再次沒有顏色格式)

Sleep Started
Sleep ended
Space down

如何在線程休眠之前讓“睡眠開始”消息發生,以及為什么當我沒有按住空格鍵時它會在第二個 if 語句中進行?

它不起作用,因為函數.Sleep()暫停您的程序。 在那個睡眠時間內沒有任何解釋。 如果你想能夠停止它,你必須使用一種更高級的編程異步方法。 您可以在多個在線資源中閱讀有關它的更多信息以進行學習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM