views:

102

answers:

3

Is there some way I can make an Extension Method asynchronous?

I have looked around for a while now, but haven't yet found anything related. Will keep looking though...

+6  A: 

To make any method asynchronous send the method a callback and have the method spin a new thread.

I whipped up a short sample in .net 3.5 (maybe Jon will show us a 4.0 sample):

 public static void Extension<T>(this T self, AsyncCallback callback )
    {
        var state = new State { callback = callback };
        System.Threading.ThreadPool.QueueUserWorkItem(ExtensionCore, callback);
    }

    private static void ExtensionCore(object state)
    {
        // do stuff with OtherStuff
        var complete = new Complete();
        ((State)state).callback(complete);
    }

    private class State
    {
        public AsyncCallback callback { get; set; }
        public object OtherStuff { get; set; }
    }

    public class Complete : IAsyncResult 
    {  
        public object AsyncState
        {
            get { throw new NotImplementedException(); }
        }

        public System.Threading.WaitHandle AsyncWaitHandle
        {
            get { throw new NotImplementedException(); }
        }

        public bool CompletedSynchronously
        {
            get { throw new NotImplementedException(); }
        }

        public bool IsCompleted
        {
            get { throw new NotImplementedException(); }
        }
    }
}
ondesertverge
Thank you for y our answer. :)
lucifer
+3  A: 

An extension method is just a normal static method, with syntactic sugar to invoke it.

So work out how you'd make a normal method asynchronous (e.g. by starting a Task within it, in .NET 4) and go from there.

Jon Skeet
Done! I like answers that make you think. :)
lucifer
Oh, where are my manners... Thank you :)
lucifer
+1  A: 

On a tangentially related note, Reactive Extensions for .NET provides extension methods that help with asynchronous programming. .NET 4 also has the Task Parallel Library (which Jon alluded to) that can help with parallelizing common operations on collections and in general greatly simplifies propagation of exceptions (even aggregating exceptions across multiple Tasks), coordination between multiple parallel tasks that must combine their results, support for cancellation and other sophisticated behaviors.

Dan Bryant