Gif 动画 XAML C# 已暂停

Gif Animation XAML C# Paused

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

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

当我想要显示图像时使用animateImage.Visibility = Visibility.Visible;

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

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

编辑

我正在 运行ning 的进程代码。我希望在 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;
}

问题是:

//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 链接多个任务,因此它们 运行 一个接一个。只需将捕获的同步上下文传递给最后一个,它设置动画可见性。

Mohammad Dehghan 真的很有帮助,他让我走上了正确的方向。但是,我看起来有些不同,所以发布了最终结果。

它去执行进程,而其他东西在后台保持 运行。

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