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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With