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这个语句是会造成界面卡死的,在多线程中慎用这个操作。
探讨了WPF中使用XAML与C#结合动画和多线程时遇到的问题,详细分析了如何通过Storyboard实现界面动画,并指出在多线程环境下调用Dispatcher.BeginInvoke可能造成的界面卡顿现象。

4311

被折叠的 条评论
为什么被折叠?



