1

I started working with delegates last week and i am trying to update my gridview async on the background. All goes well, no errors or such but i dont get a result after my EndInvoke. does anyone know what i am doing wrong?

Here is a code snippet:

    public delegate string WebServiceDelegate(DataKey key);

    protected void btnCheckAll_Click(object sender, EventArgs e)
    {
        foreach (DataKey key in gvTest.DataKeys)
        {
            WebServiceDelegate wsDelegate = new WebServiceDelegate(GetWebserviceStatus);
            wsDelegate.BeginInvoke(key, new AsyncCallback(UpdateWebserviceStatus), wsDelegate);
        }
    }

    public string GetWebserviceStatus(DataKey key)
    {
        return String.Format("Updated {0}", key.Value);
    }

    public void UpdateWebserviceStatus(IAsyncResult result)
    {
        WebServiceDelegate wsDelegate = (WebServiceDelegate)result.AsyncState;

        Label lblUpdate = (Label)gvTest.Rows[???].FindControl("lblUpdate");
        lblUpdate.Text = wsDelegate.EndInvoke(result);
    }
4

1 回答 1

0

我刚刚按照您调用它们的顺序使用相同的异步调用进行了测试。它在这里运行良好。我怀疑您在获取 Label 控件的句柄时遇到问题。试着把那条线分成几条线,以确保你得到正确的手柄。Rows 实际上返回一行吗?FindControl 是否返回您想要的控件?您可能应该在您的两个功能中检查这一点。

作为旁注,您可能只想考虑对 Rows 进行索引并使用 FindControl 一次。您需要将传递给 IAsyncResult 的对象替换为可以保存标签句柄的对象。然后你可以做一次并分配它,然后在 UpdateWebserviceStatus 中使用。

编辑:试试这个代码。

        public delegate void WebServiceDelegate(DataKey key);

    protected void btnCheckAll_Click(object sender, EventArgs e)
    {
        foreach (DataKey key in gvTest.DataKeys)
        {
            WebServiceDelegate wsDelegate = new WebServiceDelegate(GetWebserviceStatus);
            wsDelegate.BeginInvoke(key, new AsyncCallback(UpdateWebserviceStatus), wsDelegate);
        }
    }

    public void GetWebserviceStatus(DataKey key)
    {
        DataRow row = gvTest.Rows[key.Value];
        System.Diagnostics.Trace.WriteLine("Row {0} null", row == null ? "is" : "isn't");

        Label lblUpdate = (Label)row.FindControl("lblUpdate");
        System.Diagnostics.Trace.WriteLine("Label {0} null", lblUpdate == null ? "is" : "isn't");

        lblUpdate.Text = string.Format("Updated {0}", key.Value);
    }

    public void UpdateWebserviceStatus(IAsyncResult result)
    {
    WebServiceDelegate wsDelegate = (WebServiceDelegate)result.AsyncState;
    DataKey key = wsDelegate.EndInvoke(result);
    }
于 2010-04-06T13:52:46.013 回答