我有一個XAML應用程序,用作自動化的UI。整個自動化可能需要20-30小時的時間才能完全執行,因此我創建了一個基本上包裝線程方法(啓動/停止/重置)的任務類對象。WPF/XAML:如何執行線程進程並防止主UI忙/凍結?
但是,當我在Task對象下運行自動化方法時,XAML UI很忙,我無法與其他控件交互,包括切換Thread.Set()標誌的Pause按鈕。
還有另一篇文章 Prevent UI from freezing without additional threads
,其中有人推薦BackgroundWorker的類此MSDN文章提到這是一個壞主意,用這個,如果它操縱的UI,這礦的確顯示狀態,計數的目的,對象時: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
解決這個任何想法?
private void OnButtonStartAutomationClick(object sender, RoutedEventArgs e)
{
btnPauseAutomation.IsEnabled = true;
Automation.Task AutomationThread = new Automation.Task(RunFullAutomation);
}
private void RunFullAutomation()
{
// do stuff that can take 20+ hours
// threaded so I can utilize a pause button (block)
}
class Task
{
private ManualResetEvent _shutdownFlag = new ManualResetEvent(false);
private ManualResetEvent _pauseFlag = new ManualResetEvent(true);
private Thread _thread;
private readonly Action _action;
public Task(Action action)
{
_action = action;
}
public void Start()
{
ThreadStart ts = new ThreadStart(DoDelegatedMethod);
_thread = new Thread(ts);
_thread.Start();
_thread.Priority = ThreadPriority.Lowest;
}
public void Resume()
{
_pauseFlag.Set();
}
public void Stop()
{
_shutdownFlag.Set();
_pauseFlag.Set();
_thread.Join();
}
private void DoDelegatedMethod()
{
do
{
_action();
}
while (!_shutdownFlag.WaitOne(0));
}
}
請注意 - 我建議不要創建一個名爲Task的類,因爲它與框架的Task類衝突:http://msdn.microsoft.com/en-us/library/system.threading。 tasks.task.aspx – 2011-02-12 02:37:19