1

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 showed in a textBox, but is refreshed until finished the subroutine.

Is there a way where can show refresh UI?

Darf
  • 2,495
  • 5
  • 26
  • 37
  • 1
    [This question](http://stackoverflow.com/questions/6117293/synchronous-wait-without-blocking-the-ui-thread/6117313) seems to be similar/relevant. – H.B. Sep 08 '11 at 01:03

2 Answers2

5

Never sleep in the UI thread. Never. Ever.

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

EboMike
  • 76,846
  • 14
  • 164
  • 167
  • Sorry, I'm not an expert in WPF. This subroutine is executed pressing a command (button). What do you mean when you say a new thread? – Darf Sep 08 '11 at 01:02
  • @OscarFimbres: A new [Thread](http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx). See also: [Threads and Threading](http://msdn.microsoft.com/en-us/library/6kac2kdh.aspx) – H.B. Sep 08 '11 at 01:04
1

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.

Bevan
  • 43,618
  • 10
  • 81
  • 133