2016-04-08 77 views
0

我在我的程序中使用了How do I get an animated gif to work in WPF?Gif動畫XAML C#已暫停

最初在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; 
} 
+0

您需要發表更多代碼。您的流程很可能會阻止UI線程並阻止GIF播放,但您沒有提供足夠的詳細信息來說明問題。 – WasGoodDone

+0

@WasGoodDone所有的代碼都是問題中的鏈接。我所做的只是在程序中隱藏或顯示屬性。除上述內容外,還有其他哪些代碼?謝謝 – Imsa

+0

你說「我運行一個進程。」這個過程的邏輯與你遇到的問題有關,因此將該代碼作爲問題的一部分會很有幫助。 http://stackoverflow.com/help/how-to-ask – WasGoodDone

回答

1

Mohammad Dehghan真的很有幫助,並讓我朝着正確的方向前進。不過,我看起來有些不同,所以發佈結束了。

它去執行過程,而其他的東西在後臺繼續運行。

animateImage.Visibility = Visibility.Visible; 
    await Task.Run(() => 
    { 
     // Process goes here 
    }); 
animateImage.Visibility = Visibility.Hidden; 
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來鏈接許多任務,因此它們會一個接一個地運行。只需將捕獲的同步上下文傳遞給最後一個,即設置動畫可見性。

+0

我想讓它等待。我如何爲'animateImage.Visibility = Visibility.Visible'進行同步調用? – Imsa

+0

檢查編輯的答案。 –

+0

我希望animateImage對於我運行的每個進程都可見。因此,流程進入第一個'{}'和'Visibility.Visible'處於第二個'{}'。謝謝 – Imsa