Windows Phone開發經驗談(16)-使用Async CTP簡化異步編程


    Windows 8 中已經可以使用C#5.0的“異步”特性,簡單優美的代碼,大大降低異步編程的復雜性,在Windows Phone7 中也可以利用Async CTP來實現,具體方法如下.

首先下載Async CTP http://www.microsoft.com/en-us/download/details.aspx?id=9983

安裝的必要條件是Vs2010 Sp1 沒安裝Sp1的朋友請下載:http://download.microsoft.com/download/E/B/A/EBA0A152-F426-47E6-9E3F-EFB686E3CA20/VS2010SP1dvd1.iso

Async CTP下載完后不要急於安裝..因為該安裝程序和眾多VS補丁有沖突,即使安裝了也無法使用,所以我們必須先排除這些地雷。

---------------------------------------------------------------------------------------------------------------

如果是Windows 8 系統必須在沒有安裝Silverlight 5之前安裝Async CTP 否則無法使用 如果安裝了 Silverlight 5請先卸載,如果安裝了VS2012 建議也先卸載。

刪除以下補丁可以到控制面板查找:KB2635973, KB2615527, KB2645410

(具體可以參考:http://blogs.msdn.com/b/lucian/archive/2012/03/25/asyncctp-installation-problems-and-vs11.aspx

安裝完成之后在我的文檔里面就會出現Microsoft Visual Studio Async CTP 這個文件夾 找到AsyncCtpLibrary_Phone.dll 這個文件

這時候就可以新建一個Windows Phone程序 引用AsyncCtpLibrary_Phone.dll 這個DLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading.Tasks;

namespace CRSAsyncCTP
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 構造函數
        public MainPage()
        {
            InitializeComponent();
        }

        private int fun(object num)
        {
            int i = (int)num;
            if (i == 0 || i == 1) return 1;
            return i * fun(i - 1);
        }

        private async Task<int> FFun(int num)
        {
            return await Task<int>.Factory.StartNew(new Func<object, int>(fun), num);

        }

        private async void button1_Click(object sender, RoutedEventArgs e)
        {
            string str = textBox1.Text;
            int number = int.Parse(str);
            var result = await FFun(number);
            base.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(result.ToString());
            });

        }


    }
}

 

我做了個DEMO下載地址:CRSAsyncCTP.rar

好了,就介紹到這里趕快來體驗一下吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM