Question

I have this code:

void wait(int ms)
{
    System.Threading.Thread.Sleep(ms);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    info.Text = "step 1";
    wait(1000);
    info.Text = "step 2";
    wait(1000);
    info.Text = "step 3";
    wait(1000);
    info.Text = "step 4";
    wait(1000);
}

And problem is that textbox.text is updated after whole void button1_Click finished. It is not updated ON AIR :(

Please, How to do that?

Was it helpful?

Solution

Just do this.

private void button1_Click(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem((o) =>
             {
                 Dispatcher.Invoke((Action) (() => info.Text = "step 1"));
                 wait(1000);
                 Dispatcher.Invoke((Action) (() => info.Text = "step 2"));
                 wait(1000);
                 Dispatcher.Invoke((Action) (() => info.Text = "step 3"));
                 wait(1000);
                 Dispatcher.Invoke((Action) (() => info.Text = "step 4"));
                 wait(1000);
             });
    }

OTHER TIPS

The GuI Thread won't refresh until the button1_Click method returns. That's why you only see the last value. You have to put long methods into asynchronous calls or use threads.

The measure/arrange (and therefore the render) happens asynchronously so if you want to force the screen to update then you would need to call UpdateLayout.

What if you tried a DispatcherFrame to simulate what forms DoEvents would accomplish:

You may need to include System.Security.Permissions and System.Windows.Threading. After that pplace a call to DoEvents() after each of your sleeps and you get the desired result.

[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public void DoEvents()
{
    DispatcherFrame frame = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
        new DispatcherOperationCallback(ExitFrame), frame);
    Dispatcher.PushFrame(frame);
}

public object ExitFrame(object f)
{
    ((DispatcherFrame)f).Continue = false;

    return null;
}

Link to MSDN article: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.pushframe.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top