Asynchronously update UI elements in WPF

Source: Internet
Author: User

XAML

The interface is very simple. There is only one button and one lable element. to click the button, the content of the lable will automatically increase from 0.

<Grid>    <Label Name="lable_plus" Content="0"/>    <Button Content="Button"  Click="button_Click" Height="23"  Name="button" Width="75" /></Grid>

C #

private void button_Click(object sender, RoutedEventArgs e){     for (int i = 0; i < 100000; i++)     {                         lable_plus.Content = i;     }}

After the above code is executed, you will find that clicking the button does not show up; the number in lable increases progressively, but after a moment, 99999 appears directly. The reason is that the UI thread is blocked to calculate the cyclic I ++.

Method 1:

private void te_Click(object sender, RoutedEventArgs e){       update();            }public delegate void PlusNumberDelegate(int i);private void update(){      for (int i = 0; i < 100000; i++)     {                           this.lable_plus.Dispatcher.BeginInvoke(                    DispatcherPriority.SystemIdle,           new NextNumber(this.plus),i);     }}

Reference http://msdn.microsoft.com/zh-cn/library/ms741870.aspx

Method 2:

 

Real score

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.