如何从使用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
?
无论如何,感谢您的反馈。
答案 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"
}