开发者

How can I update the UI when I use Thread.Sleep

开发者 https://www.devze.com 2023-04-03 04:26 出处:网络
This is the function which I\'m using: private void Convert2Morse(object obj) { TextConverted = am.Convert(NormalText);

This is the function which I'm using:

    private void Convert2Morse(object obj)
    {
        TextConverted = am.Convert(NormalText);

        foreach (char symbol in TextConverted)
        {
            int milliseconds = 0;

            switch (symbol)
            {
                case '·': milliseconds = 500; break;
                case '—': milliseconds = 1000; break;
                case ' ': continue;
                default: throw new Exception("Something is wrong");
            }

            System.Media.SystemSounds.Beep.Play();
            System.Threading.Thread.Sleep(milliseconds);
        }
    }

The TextConverted property is开发者_StackOverflow社区 showed in a textBox, but is refreshed until finished the subroutine.

Is there a way where can show refresh UI?


Never sleep in the UI thread. Never. Ever.

You need to create a new thread to play your sounds.


Within an WPF application, you can have multiple "threads" of execution - independent flows of control that are active within the same process.

The approach you've taken in your code has everything happening on the user interface thread - this is the thread responsible for repainting the screen. When this thread is busy running your morse code routine, it can't do any repainting.

What you need to do is to move execution of your morse code routine onto a separate thread - this will allow the UI thread to handle repainting in a timely fashion. The easiest way to achieve this is to use a BackgroundWorker object. (Most examples you'll find online for this use WinForms, but it works fine with WPF too.)

Note however, that you're getting into a moderately complex area of development. Based on your comment to @EboMike, you're going to find this a challenge - there are a lot of new concepts to get your head around. One good place to start might be the Beginners guide to threading on CodeProject. (I found this with a google search and the first few paragraphs read Ok - YMMV.)

Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消