XAML:
1 <StackPanel x:Name="LayoutBoot">
2 <!--创建border-->
3 <Border x:Name="border" Background="AliceBlue" Margin="5"
4 BorderBrush="Black" BorderThickness="3" CornerRadius="5">
5 </Border>
6 <!--内嵌一个stackpanel画板-->
7 <StackPanel Orientation="Horizontal">
8 <!--开始线程按钮-->
9 <Button x:Name="btnStart" Width="100" Height="30"
10 Content="开始线程"
11 Click="btnStart_Click" Margin="10">
12 </Button>
13 <!--延时线程按钮-->
14 <Button x:Name="btnDelay" Width="100" Height="30"
15 Content="延时2s"
16 Click="btnDelay_Click" Margin="10">
17 </Button>
18 </StackPanel>
19 </StackPanel>
C#:
1 namespace ThreadSample
2 {
3 public partial class MainPage : UserControl
4 {
5 private static TextBlock tbk;
6 private System.Threading.Thread myThread;
7 public MainPage()
8 {
9 InitializeComponent();
10 //添加文本控件tbk
11 tbk = new TextBlock()
12 {
13 FontSize=24,
14 Width=300,
15 Height=100
16 };
17 //动态加载对象tbk
18 border.Child = tbk;
19 //创建新线程
20 myThread = new Thread(new ThreadStart(SetText));
21 //设置为后台线程
22 myThread.IsBackground = true;
23 }
24
25 public static void SetText()
26 {
27 int i = 60;
28 while (i > 0)
29 {
30 tbk.Dispatcher.BeginInvoke(delegate()
31 {
32 tbk.Text = "离线程结束还有 " + i + " 秒";
33 });
34 i--;
35 Thread.Sleep(1000);
36 }
37 }
38
39 private void btnStart_Click(object sender, RoutedEventArgs e)
40 {
41 myThread.Start();
42 }
43
44 private void btnDelay_Click(object sender, RoutedEventArgs e)
45 {
46 myThread.Join(2000);
47 }
48 }
49 }
效果: