简体   繁体   中英

AsyncCallBack passed as a method parameter

I'm trying to pass a method as AsyncCallBack parameter from Class1 to Class2 like this:

public class Class1
{
    public void MyTestCallBack()
    {
        Class2 c2 = new Class2();
        c2.TestCallbackAPM(MyCallBack);//How can i pass MyCallBack method as parameter and use it in class2 as AsyncCallBack?
    }
    public void MyCallBack(IAsyncResult result)
    {
         //....     
    }

}

public class Class2
{   
     public void TestCallbackAPM(/*MyCallBackMethod*/ CompleteRead)//How can i pass MyCallBack method as parameter and use it in class2 as AsyncCallBack?
     {
        string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");

        FileStream strm = new FileStream(filename,
        FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
        FileOptions.Asynchronous);

        // Make the asynchronous call
        IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
        new AsyncCallback(CompleteRead), strm);
     }
}

How can I pass MyCallBack as parameter from Class1 to Class2 ?

One possibility would be to use the predefined delegate Action<T> :

Encapsulates a method that has a single parameter and does not return a value.

In your case use Action<IAsyncResult> callbackMethod as a parameter to the method - it matches exactly void MyCallBack(IAsyncResult result) :

public class Class2
{   
     public void TestCallbackAPM(Action<IAsyncResult> CompleteRead)
     {
     }
}

If you do not want to use the predefined Action delegate, then create your own:

public delegate void MyCallBackMethod(IAsyncResult result);

The usage is the same:

public class Class2
{   
     public void TestCallbackAPM(MyCallBackMethod CompleteRead)
     {
     }
}

If you want to pass a method that returns a value, then you can use the predefined Func<T, TResult> delegate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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