0

如何从Func<t>使用 BeginInvoke 调用的函数中获取值?

例如:

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"
}

我是否必须将其转换为 AsyncCallback 然后调用EndInvoke

无论如何,感谢您的反馈。

4

1 回答 1

3

AsyncState保存null您作为第二个参数传入的参数,您应该传入该foo对象。要获得结果,您必须EndInvoke从 foo 对象调用,它将返回结果的对象版本。

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"
}
于 2013-08-15T19:48:24.187 回答