2011-05-27 65 views
0

我有一個運行函數的應用程序可能需要花費大量時間,所以我需要添加一個回調方法。我將如何去做這件事?在WP7中實現回調C#

主要是,我的問題是什麼是需要傳遞給類構造函數的類型?

回答

4

在C#上(不僅在WP7上),您可以通過將其包裝在委託中來異步調用任何函數。在委託的BeginInvoke調用中,您將傳遞一個回調,該操作完成後將調用該回調。看下面的例子:

int MyLongOperation(int x, int y) { 
    Thread.Sleep(10000); 
    return x+y; 
} 

void CallingLongOperation(){ 
    int x = 4; 
    int y = 5; 
    Func<int, int, int> func = MyLongOperation; 
    func.BeginInvoke(x, y, OperationCallback, func); 
} 

void OperationCallback(IAsyncResult asyncResult) { 
    Func<int, int, int> func = (Func<int, int, int>) asyncResult.AsyncState; 
    int result = func.EndInvoke(asyncResult); 
    // do something with the result 
} 

如果你需要傳遞一些附加參數在asyncState/userState屬性,您還可以使用的IAsyncResult參數的AsyncDelegate特性(這對於委託調用總是System.Runtime.Remoting .Messaging.AsyncResult),並從那裏檢索委託,如下所示。

public int MyLongOperation(int x, int y) 
{ 
    Thread.Sleep(10000); 
    return x + y; 
} 
public void CallLongOperation() 
{ 
    Func<int, int, int> func = MyLongOperation; 
    func.BeginInvoke(5, 7, MyCallback, "Expected result: " + 12); 
    Console.WriteLine("Called BeginInvoke"); 
    func.BeginInvoke(11, 22, MyCallback, "Expected result: " + 33); 
    Console.WriteLine("Press ENTER to continue"); 
    Console.ReadLine(); 
} 
void MyCallback(IAsyncResult asyncResult) 
{ 
    Func<int, int, int> func = (Func<int, int, int>)((System.Runtime.Remoting.Messaging.AsyncResult)asyncResult).AsyncDelegate; 
    string expectedResult = (string)asyncResult.AsyncState; 
    int result = func.EndInvoke(asyncResult); 
    Console.WriteLine("Result: {0} - {1}", result, expectedResult); 
} 
+0

委託不能在.NET Compact Framework上因此異步調用,因此WP7。 – 2012-04-27 04:00:08