如何将参数传递给回调?

时间:2010-12-14 08:49:33

标签: c# wpf

C#中的代码回调:

private void CallbackVisibleButton(IAsyncResult ar)
{
    AsynchronousVisibleButtonDelegate asyncDeleg = (AsynchronousVisibleButtonDelegate)ar.AsyncState;
    b.Visibility = asyncDeleg.EndInvoke(ar);// b - not see!
}
private delegate Visibility AsynchronousVisibleButtonDelegate(Button b);
private Visibility AsynchronousVisibleButton(Button b)
{
    Thread.Sleep(2000);
    return Visibility.Visible;
}

并创建(b是按钮,应该看到按钮后5秒):

AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
AsyncCallback callback = new AsyncCallback(CallbackVisibleButton);
asyncDeleg.BeginInvoke(b, callback, asyncDeleg);

问题:CallbackVisibleButton - 没有看到按钮

2 个答案:

答案 0 :(得分:1)

使用BeginInvoke的第三个参数发送额外信息。那么你可以通过IAsyncResult.AsyncState属性获得它。

这是一个例子:http://progtutorials.tripod.com/C_Sharp.htm

答案 1 :(得分:1)

也许下面的代码可以解决您的问题。删除CallBackVisib ...方法并在主代码中执行以下操作:

        AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
        AsyncCallback callback = new AsyncCallback(p =>
                                                       {
                                                           var anotherState =
                                                               p.AsyncState as AsynchronousVisibleButtonDelegate;
                                                           b.Visible = anotherState.EndInvoke(p);
                                                       });
        asyncDeleg.BeginInvoke(b, callback, asyncDeleg);