XAML代碼:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Storyboard x:Key="OnLoaded1" RepeatBehavior="Forever">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Line.X1)">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="16"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Grid>
<Line Height="208" Margin="12,0,0,0" Name="line7" Stroke="Red" StrokeDashArray="3" StrokeDashCap="Triangle" StrokeThickness="3" VerticalAlignment="Bottom" X1="0" X2="500" Y1="3" Y2="3" Canvas.Top="269" Canvas.Left="204" />
</Grid>
</Window>
c#代碼:
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.Windows.Media.Animation;
using System.Threading;
namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Storyboard Right;
Right = (Storyboard)this.FindResource("OnLoaded1");
line7.BeginStoryboard(Right);
Thread newThread = new Thread(new ThreadStart(ThreadStart));
newThread.IsBackground = true;
newThread.Start();
}
private void ThreadStart()
{
int n = 0;
while (true)
{
Thread.Sleep(1000);
//每5秒鐘調用一次
n++;
if (n == 5)
{
n = 0;
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(delegate
{
try
{
Thread.Sleep(1000);
}
catch (Exception)
{
}
}));
}
}
}
}
}
運行上面這個簡單的demo,發現每隔5秒鐘界面動畫就會卡死1秒。
因此 System.Windows.Application.Current.Dispatcher.BeginInvoke這個語句是會造成界面卡死的,在多線程中慎用這個操作。