DownloadStringCompletedEventHandler在另一个类中回调

时间:2012-11-20 11:12:53

标签: c# callback

我有两个课程,下面是关于我继续问我的问题之前发生的事情......

MyClass1的:

myClass1(){

    myClass2 c2 = new myClass2();
    c2.service();

}

public void myFunction1(){

    Console.Write("Function returned!");

}

myClass2:

public void service(){

    callWebService(myFunction1); // The parameter you pass here is the function that control 
                      // will pass back to once the called function is done.

}

public void callWebService(DownloadStringCompletedEventHandler callback){

    //Calls web service and does some other operations

}

最后一个问题。正如你在上面看到的,我有2个类,class1在class2中调用一个函数。该函数在class2中调用另一个调用webservice的函数。完成Web服务后,控制流将返回到您在函数调用中传递的任何函数。

但这意味着你要坚持一个类,因为回调函数应该在同一个类中。所以问题是,如何将另一个类中的函数作为回调函数传递?

希望这一切都有道理,请不要犹豫,要求任何事情清理一下。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以修改Service类并将MyClass1's方法传递给它。例如,在下面的代码中,函数ServiceCallComplete作为参数传递给Service类构造函数。

该函数可以保存为ActionFunc委托类型(取决于您的回调函数定义)。一旦服务作业完成,调用委托(_callBack())将在MyClass1上调用回调函数。

public class MyClass1
{
    //The callback Function
    public void ServiceCallComplete()
    {
        Console.WriteLine("Function returned.");
    }

}

public class Service
{
    //delegate to store the callback function.
    private readonly Action _callBack;

    public Service(Action callBack)
    {
        //store the callback function
        _callBack = callBack;
    }

    public void Method()
    {
        //long running operation
        .
        .
       //Invoke the callback
        _callBack();
    }
}


MyClass1 obj = new MyClass1();
Service svc = new Service(obj.ServiceCallComplete);
svc.Method();

答案 1 :(得分:1)

使用事件:

,而不是传递委托
class MyClass1
{
    public MyClass1()
    {
        var c2 = new MyClass2();

        c2.ActionwebServiceCalled += MyCallBack; //register for the event
        c2.CallWebService();
    }

    public void MyCallBack(object sender, DownloadStringCompletedEventArgs e)
    {
        Console.Write("Function returned!");
    }
}

class MyClass2
{
    public event DownloadStringCompletedEventHandler ActionwebServiceCalled;

    public void CallWebService()
    {
        DownloadStringCompletedEventArgs e = null;

        //Calls web service and does some other operations...

        var handler = ActionwebServiceCalled;
        if (handler != null)
            handler(this, e);
    }
}

话虽如此,您可能希望在Web服务调用中引入异步,在这种情况下Task-based Asynchronous Pattern (TAP)是可行的方法,只要您拥有.NET 4(or Rx) 。对于.NET 3.5及更低版本,您需要遵循Asynchronous Programming Model (APM)