在WP7 C#中实现回调

时间:2011-05-27 22:23:05

标签: c# windows-phone-7 callback

我有一个应用程序运行一个可能需要相当长时间的功能,所以我需要添加一个回调方法。我该怎么做呢?

主要是,我的问题是需要传递给类构造函数的类型是什么?

1 个答案:

答案 0 :(得分: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);
}