简体   繁体   English

在 WP7 C# 中实现回调

[英]Implementing Callback in WP7 C#

I have an app that runs a function that could take a decent amount of time, so I need to add a callback method.我有一个运行 function 的应用程序可能需要相当长的时间,所以我需要添加一个回调方法。 How would I go about this?我将如何 go 关于这个?

Mainly, my question is what is the type that needs to be passed to the class constructor?主要是,我的问题是需要传递给 class 构造函数的类型是什么?

On C# (not only on WP7) you can call any function asynchronously by wrapping it in a delegate.在 C#(不仅在 WP7 上)上,您可以通过将任何 function 包装在委托中来异步调用它。 On the delegate's BeginInvoke call you'd pass a callback which will be invoked when the operation is completed.在委托的 BeginInvoke 调用中,您将传递一个回调,该回调将在操作完成时调用。 See the example below:请参见下面的示例:

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
}

If you need to pass some additional parameter in the asyncState / userState property, you can also use the AsyncDelegate property of the IAsyncResult parameter (which for delegate calls is always System.Runtime.Remoting.Messaging.AsyncResult) and retrieve the delegate from there as well, as shown below.如果您需要在 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM