Pause execution of a method without locking GUI. C#

前端 未结 4 1535
孤街浪徒
孤街浪徒 2020-12-30 16:19

I\'m working on a card game in C# for a project on my Intro to OOP paper and have got the game working now but am adding \"flair\" to the GUI.

Currently cards are de

4条回答
  •  礼貌的吻别
    2020-12-30 16:43

    The problem is that any code that you run on the UI will block the UI and freeze the program. When your code is running (even if it's running Thread.Sleep), messages (such as Paint or Click) sent to the UI will not be processed (until control returns to the message loop when you exit your event handler), causing it to freeze.

    The best way to do this is to run on a background thread, and then Invoke to the UI thread between sleeps, like this:

    //From the UI thread,
    ThreadPool.QueueUserWorkItem(delegate {
        //This code runs on a backround thread.
        //It will not block the UI.
        //However, you can't manipulate the UI from here.
        //Instead, call Invoke.
        Invoke(new Action(delegate { cardImage1.Image = playDeck.deal().show(); }));
        Thread.Sleep(100);
    
        Invoke(new Action(delegate { cardImage2.Image = playDeck.deal().show(); }));
        Thread.Sleep(100);
    
        Invoke(new Action(delegate { cardImage3.Image = playDeck.deal().show(); }));
        Thread.Sleep(100);
    
        //etc...
    });
    //The UI thread will continue while the delegate runs in the background.
    

    Alternatively, you could make a timer and show each image in the next timer tick. If you use a timer, all you should do at the beginning is start the timer; don't wait for it or you'll introduce the same problem.

提交回复
热议问题