Search code examples
c#asynchronousiasyncresult

Too many arguments in BeginXXX for FromAsync?


I have an async method with the following signature:

IAsyncResult BeginGetMyNumber(string foo, string bar, string bat, int bam, AsyncCallback callback, object state)

I want to execute it using Factory.FromAsync like this:

var result  = Task<int>.Factory.FromAsync(
                instance.BeginGetMyNumber, 
                instance.EndGetMyNumber, 
                "foo",
                "bar",
                "bat",
                100, /*bam*/
                null);

but I get the following error:

Argument 1: cannot convert from 'method group' to 'System.Func'

It seems there is no suitable overloaded FromAsync method http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx, it only supports up to 5 arguments (including callback and state) on the BeginXXX method.

Other than refactoring the BeginXXX method to take an object rather than six arguments, is there a way to execute it using FromAsync?


Solution

  • Actually it seems I can use the overloaded method for Factory.FromAsync( that takes an IAsyncResult object as the first argument and a callback method as the second:

    result = Task<string>.Factory.FromAsync(
                    instance.BeginGetMyNumber("foo", "bar", "bat", 1, null, null),
                    instance.EndGetMyNumber);