GIF动画XAML C#暂停

时间:2016-04-08 18:02:59

标签: wpf multithreading xaml gif animated-gif

我在我的程序中使用How do I get an animated gif to work in WPF?

最初在XAML中,我设置了Visibility="Hidden"

在我想要显示图片时使用animateImage.Visibility = Visibility.Visible;

在显示图像后,我运行了一个过程。但是,只要进程开始,动画就会暂停。 我想知道它为什么这样做?

我正在考虑创建一个新线程并在线程中运行GIF,并在进程完成时关闭线程。

修改

我正在运行的进程的代码。我想在GPUpdate期间播放动画。

ExecProc("gpupdate", "/force");

private static bool ExecProc(string file, string arg)
{
    bool flag = true;
    try
    {
        //Create a new process info structure.
        ProcessStartInfo pInfo = new ProcessStartInfo();
        pInfo.FileName = file;
        pInfo.CreateNoWindow = true;
        pInfo.Arguments = arg;
        pInfo.WindowStyle = ProcessWindowStyle.Hidden;

        Process ps = new Process();
        ps.StartInfo = pInfo;
        ps.Start();

        //Wait for the process to end.
        ps.WaitForExit();
    }
    catch (Exception e)
    {
        writeLog("Error: " + e + " running " + file + " " + arg);
        flag = false;
    }
    return flag;
}

2 个答案:

答案 0 :(得分:1)

问题在于:

//Wait for the process to end.
ps.WaitForExit();

您正在阻止UI线程,等待该过程完成。

如果需要在进程完成时收到通知,请在另一个线程中执行该操作,然后在UI线程上调用回调:

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
animateImage.Visibility = Visibility.Visible;
Task.Run(() =>
    {
        // Start the process and wait for it to finish, as you did before.
    }).ContinueWith(task =>
    {
        animateImage.Visibility = Visibility.Hidden;
        // Do whatever you need to do when the process is finished.
    }, uiScheduler);

Task.Run触发一个线程并在该线程中执行任务(它实际上使用线程池,并且不创建新线程)。 ContinueWith执行相同的操作,但在上一个任务完成后启动任务。

TaskScheduler.FromCurrentSynchronizationContext()从主线程捕获同步上下文。将该同步上下文传递给ContinueWith会导致它在主(UI)线程中触发任务,这在操作UI控件时是必需的。

您可以使用多个ContinueWith来链接许多任务,因此它们会一个接一个地运行。只需将捕获的同步上下文传递给最后一个,即设置动画可见性。

答案 1 :(得分:1)

Mohammad Dehghan真的很有帮助,让我朝着正确的方向前进。但是,我看起来略有不同,所以发布了最终结果。

当其他内容在后台继续运行时,它会继续执行该过程。

animateImage.Visibility = Visibility.Visible;
    await Task.Run(() =>
    {
        // Process goes here
    });
animateImage.Visibility = Visibility.Hidden;