简体   繁体   中英

Implement Classic Async Pattern using TPL

I'm trying to implement a custom TrackingParticipant for WF 4. I can write the Track method, but my implementation will be slow.

How can I implement the Begin/EndTrack overrides using .NET 4.0's Task Parallel Library (TPL)? I've looked at TPL and Traditional .NET Asynchronous Programming but am not sure how to apply it here.

Note that TrackingParticipant is part of .NET and has the Classic Async Pattern predefined using virtual methods.

public class MyTrackingParticipant : TrackingParticipant
{
    protected override IAsyncResult BeginTrack(
        TrackingRecord record, TimeSpan timeout,
        AsyncCallback callback, object state)
    {
        // ?
    }

    protected override void EndTrack(IAsyncResult result)
    {
        // ?
    }

    protected override void Track(TrackingRecord record, TimeSpan timeout)
    {
        // synchronous code to be called
    }
}

This is the generic pattern with which to implement the classic APM programming model:

protected override IAsyncResult BeginTrack(TrackingRecord record, TimeSpan timeout, AsyncCallback callback, object state)
{
    Task result = Task.Factory.StartNew(
        (taskState) =>
        {
           // ... your async work here ...
        },
        state);

    if(callback != null)
    {
        result.ContinueWith((t) => callback(t));
    }

    return result;
}

protected override void EndTrack(IAsyncResult asyncResult)
{
   // Call wait to block until task is complete and/or cause any exceptions that occurred to propagate to the caller
   ((Task)asyncResult).Wait();
}

If the EndXXX method returned a result you would actually return the Result property of the Task instead of just calling Wait . For example:

protected override int EndAwesomeCalculation(IAsyncResult asyncResult)
{
   // This will block until the result is available and/or cause any exceptions that occurred propagate to the caller
   return ((Task<int>)asyncResult).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