我有一个网页 MyWebPage.aspx,它在加载时必须显示来自两个 web 服务的数据以及它自己的算法。
1) WebServiceI.SomeMethod() -> Takes 10 seconds aprx. to respond.
2) WebServiceII.SomeMethod() -> Takes 10 seconds aprx. to respond.
3) My Algorithm -> Takes 5 second aprx to respond.
现在,当我同步调用它时,加载需要 10+10+5 = 25 秒。
所以,有人建议我使用“异步调用方法”,即使用 IAsyncResult/AsyncCallback。现在将(应该)发生的是所有将同时调用并且页面将在最多 10 秒内加载。
所以我现在以“开始/结束”的方式称呼他们......
public partial class MyWebPage : System.Web.UI.Page
{
WebServiceI WebServiceIObject = new WebServiceI();
WebServiceII WebServiceIIObject = new WebServiceII();
protected void Page_Load(object sender, EventArgs e)
{
//BeginSomeMethod(AsyncCallback callback, object asyncState)[<- Method Signature]
WebServiceIObject.BeginSomeMethod(OnEndGetWebServiceISomeMethodResult, null);
//BeginSomeMethod(AsyncCallback callback, object asyncState)[<- Method Signature]
WebServiceIIObject.BeginSomeMethod(OnEndGetWebServiceIISomeMethodResult, null);
/* My Algorithm 5 seconds*/
DataSet DS = GetDataSetFromSomeWhere();
MyGataGrid.DataSource = DS.tables[0];
MyGataGrid.DataBind();
/* My Algorithm 5 seconds*/
//System.Threading.Thread.Sleep(6000);
}
//Will be called after 10 seconds
void OnEndGetWebServiceISomeMethodResult(IAsyncResult asyncResult)
{
string WebServiceISomeMethodResult = WebServiceIObject.EndSomeMethod(asyncResult);
MyLabelI.Text = WebServiceISomeMethodResult;
//EventLog MyLog = new EventLog("Application"); MyLog.Source = "MySourceI";
//MyLog.WriteEntry(DateTime.Now.ToString());
}
//Will be called after 10 seconds
void OnEndGetWebServiceIISomeMethodResult(IAsyncResult asyncResult)
{
string WebServiceIISomeMethodResult = WebServiceIIObject.EndSomeMethod(asyncResult);
MyLabelII.Text = WebServiceIISomeMethodResult;
//EventLog MyLog = new EventLog("Application"); MyLog.Source = "MySourceII";
//MyLog.WriteEntry(DateTime.Now.ToString());
}
}
现在上面示例的问题是 MyLabelI 和 MyLabelII 文本从未设置,因为页面在 5 秒后加载
并且线程被释放。通过写入 EventLog 来检查两个结束方法都被正确调用。我该如何解决这个问题......像“所有都立即开始,然后都等到所有完成......”我知道如果我的执行线程再等待 5 秒,那么代码将按要求执行..
我应该如何使用 AsyncWaitHandle...