如何从Func <t>获取名为async?</t>的值

时间:2013-08-15 19:42:09

标签: c# .net asynchronous func

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

例如:

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

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

1 个答案:

答案 0 :(得分:3)

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

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