2014年11月12日 星期三

[C#] Async Lambda as delegate

目標:透過.NET Framework 4.5後的Async Lambda建立非同步委派。

1.      原始非同步程式碼:

u  主程式
static void Main(string[] args)
{
var myNumbers = new List<int>(){
                10,20,30,40,50,60,70,80,90,100,110,120,15
            };
//Async Test
testAsync(myNumbers);

Console.WriteLine("End");
Console.ReadKey();
}

private static void testAsync (IEnumerable<int> myNumbers)
{
using (var asyncTest = new AsyncLambda()){
    asyncTest.AsyncGetData(myNumbers); //Call async method directly
}
}

u  AsyncLambda

public class AsyncLambda : IDisposable
{
public async Task<IEnumerable<int>> AsyncGetData(IEnumerable<int> myNumbers)
{
            await Task.Delay(3000);
            var filteredData = myNumbers.Where(x => x < 100);

            foreach (var num in filteredData)
                Console.WriteLine(num.ToString());
            return filteredData;
}
}


u  Output :
End
10
20
30
40
50
60
70
80
90
15



2.      Async Lambda as a delegate
u  將原有的非同步方法改成委派(Func) :

注意在Lambda前面必須宣告一個 async (非同步)
public void GetCollection(IEnumerable<int> myNumbers)
{
    Func<IEnumerable<int>, Task<IEnumerable<int>>> myEvent = async (x) =>
            {
                await Task.Delay(3000);
                var filteredData = x.Where(p => p < 100);

                foreach (var num in filteredData)
                    Console.WriteLine(num.ToString());
                return filteredData;
            };

   myEvent.Invoke(myNumbers);
}


u  主程式改一下叫用的方法
private static void testAsyncLambda(IEnumerable<int> myNumbers)
{
using (var asyncTest = new AsyncLambda())
{
asyncTest.GetCollection(myNumbers); //Using async delegate
     //asyncTest.AsyncGetData(myNumbers); //Call async method directly
}
}


u  Output :
End
10
20
30
40
50
60
70
80
90
15



沒有留言:

張貼留言