如何从Func<;t>;称为async

本文关键字:称为 async gt lt Func | 更新日期: 2023-09-27 18:27:46

如何从使用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

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

如何从Func<;t>;称为async

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