β

利用C# .net在WP8里面异步加载任务

IT路人 546 阅读

Windows Phone 8的第一个版本也放出来有一段时间了,不知道大家有木有接触到wp8的任务功能:我自己是无缘的了,因为我呢,根本不喜欢windows Phone 8。不过呢,这个操作系统现在被视为Android和iOS的劲敌,加上微软宣传广告极度无趣,是以关注。不过呢,我们今天要看的不是这个系统怎么样怎么样,而是要看看在WP8里面如何异步加载任务列表。这里呢,用到的是WPF(Windows Presentation Foundation)或者说是C# .net。

函数

namespace AsynchronousTasks{   
    public partial class MainPage : PhoneApplicationPage{   
        List<Action> todoList = new List<Action>();   
        List<StackPanel> UIElements = new List<StackPanel>();   
        public MainPage() {   
            InitializeComponent();    
            UIElements.Add(Task1Panel);   
            UIElements.Add(Task2Panel);   
            UIElements.Add(Task3Panel);   
            UIElements.Add(Task4Panel);   
            todoList.Add(() => boringTask(0));   
            todoList.Add(() => boringTask(1));   
            todoList.Add(() => boringTask(2));   
            todoList.Add(() => boringTask(3));   
        }   
        private void boringTask(int index) {   
            for (int i = 0; i < 100; i++) {   
                for (int j = 0; j < 10000000; j++) ;   
                this.Dispatcher.BeginInvoke(new Action(()=>{   
                    ProgressBar pgBar = UIElements[index].Children[3] as ProgressBar;   
                    double step = 1;                   
                    pgBar.Value += step;   
                }));   
            }   
        }   
        public async void performAllTasks() {   
            for (int k = 0; k < todoList.Count; k++) {   
                Image bullet = UIElements[k].Children[0] as Image;   
                Image chk = UIElements[k].Children[1] as Image;   
                ProgressBar pgBar = UIElements[k].Children[3] as ProgressBar;   
                bullet.Visibility = System.Windows.Visibility.Visible;   
                chk.Visibility = System.Windows.Visibility.Collapsed;   
                Action taskTodo = todoList[k];   
                await Task.Run(()=>taskTodo());   
                bullet.Visibility = System.Windows.Visibility.Collapsed;   
                chk.Visibility = System.Windows.Visibility.Visible;   
                pgBar.Visibility = System.Windows.Visibility.Collapsed;   
            }   
        }   
        private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e) {   
            performAllTasks();   
        }   
    }   
}

声明: 本文采用 BY-NC-SA 协议进行授权 | IT路人
转载请注明转自《利用C# .net在WP8里面异步加载任务

作者:IT路人
做最好的PHP、Javascrip、HTML5等代码分享站点
原文地址:利用C# .net在WP8里面异步加载任务, 感谢原作者分享。

发表评论