Question

How do you get the value from a Func<t> that is called using BeginInvoke?

For example:

private void MyTest()
{
    Func<string> foo = Bar;

    foo.BeginInvoke(BarComplete, null);
}

private string Bar()
{
    return "Success";
}

private void BarComplete(IAsyncResult ar)
{
    var result = (string) ar.AsyncState;

    Console.WriteLine(result); // Should print "Success"
}

Do I have to cast this to an AsyncCallback and then call EndInvoke?

Anyways, thanks for the feedback.

Was it helpful?

Solution

AsyncState holds the null you passed in as a 2nd parameter, you should pass the foo object in instead. To get the result you must call EndInvoke from the foo object and it will return a object version of the result.

private void MyTest()
{
    Func<string> foo = Bar;

    foo.BeginInvoke(BarComplete, foo);
}

private string Bar()
{
    return "Success";
}

private void BarComplete(IAsyncResult ar)
{
    var foo = (Func<string>)ar.AsyncState;
    var uncastResult = foo.EndInvoke(ar); //This returns a "object", but it would still work with WriteLine
    var castResult = (string)uncastResult;

    Console.WriteLine(uncastResult); // Should print "Success"
    Console.WriteLine(castResult); // Should also print "Success"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top