D31_01_多线程

image

 

 

<Window x:Class="demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <StackPanel Margin="5">
        <TextBox Name="txt">Text in a text box.</TextBox>
        <Button Click="cmdBreakRules_Click">Break the rules</Button>
        <Button Click="cmdFollowRules_Click">Follow the rules</Button>
    </StackPanel>
</Window>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;

namespace demo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }


        private void UpdateTextWrong()
        {
            Thread.Sleep(TimeSpan.FromSeconds(3));
            txt.Text = "Here is some new text.";
        }

        private void cmdFollowRules_Click(object sender, RoutedEventArgs e)
        {
            Thread thread=new Thread(UpdateTextRight);
            thread.Start();
        }

        private void UpdateTextRight()
        {
            Thread.Sleep(TimeSpan.FromSeconds(3));

            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                UpdateTextWrong();
            });
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            //{
            //    //Thread.Sleep(TimeSpan.FromSeconds(3));耗时代码不能写在这里;这里用的是匿名委托
            //    txt.Text = "Here is some new text.";
            //});
        }


        private void cmdBreakRules_Click(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(UpdateTextWrong);
            thread.Start();
        }
    }
}
posted @ 2014-11-07 06:55  xiepengtest  阅读(112)  评论(0编辑  收藏  举报