简体   繁体   中英

Convert an Async method to use Task Parallel Library

Suppose I have the following method signature for an Async method:

public IAsyncResult MyAsyncMethod(AsyncCallback asyncCallback, object state);

And, therefore, I use the following code to call it and assign it a state object and a callback:

public class test
{
    // Private class to hold / pass-through data used by Async operations
    private class StateData
    {
        //... Whatever properties I'll need passed to my callback ...
    }

    public void RunOnSeparateThread()
    {
        StateData stateData = new StateData { ... };
        MyAsyncMethod(m_asyncCallback, stateData);
    }

    private AsyncCallback m_asyncCallback = new AsyncCallback(AsyncComplete);
    private static void AsyncComplete(IAsyncResult result)
    { 
        // Whatever stuff needs to be done after completion of Async method
        // using data returned in the stateData object
    }
}

I'm looking to do the same thing using Task Parallel Library and am not certain how to do it. What would be the correct code to achieve the same result, being:

  1. Run MyAsyncMethod on a separate thread
  2. On completion have a state object returned with it passed to the next method - In this case AsyncComplete

Or is there a better way to accomplish the same result?

Also, although this is written in C#, I'm equally comfortable in VB and C#, so any answer would be greatly appreciated.

Thank you and hopefully this makes sense.

Suppose I have the following method signature for an Async method:

 public IAsyncResult MyAsyncMethod(AsyncCallback asyncCallback, object state); 

I would expect the return value to be Task<T> ( IAsyncResult is normally returned from the BeginXYZ when there is a matching EndXYZ in the original .NET async pattern), and not taking a callback. (As presented it seems to be a bit of one pattern and a bit of another.)

If my expectation is right then, just call the method and use the retuned Task<T> .

If it is really a IAsyncResult then TaskFactory has a helper method: FromAsync which amongst its many overloads can take an IAsyncResult and an Action<IAsyncResult> .

So your code becomes:

var ia = MyAsyncMethod(() => {}, null);
var t = Task.Factory.FromAsync(ia, x => { 
    // called with ia from MyAsyncMethod on completion.
    //  Can close over any state
});

// ...
var result = (TypeofResult)t.Result;

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