我有一組我在Page_Load事件中調用的方法。
一些方法最終調用Web服務。大多數方法都是以同步的方式依次執行[一個接一個],因爲一個方法的輸出是另一個方法的輸入。從ASP.NET異步調用方法,然後更新UI上的控件
但是,這些服務調用之間可以運行的方法很少。因爲所有的操作都需要相當長的時間才能執行,所以我試圖以異步的方式運行其中的一些操作,這樣少數操作就可以並行運行。
但是,如果我將這些控件設置在回調函數中,我沒有成功更新UI上的控件,因爲我猜測回調本質上是在主「頁面回發請求」線程的不同線程中運行的。有沒有一種方法可以在回調方法中設置我的控件,然後在UI上異步更新它們。下面是代碼示例:
public partial class _Default : System.Web.UI.Page
{
public delegate string foo(string param1, string param2, ArrayList list, out ArrayList outList);
protected void Page_Load(object sender, EventArgs e)
{
Thread.Sleep(1000);
txtTextSync.Text = "my control";
CallOperationAsync();
Thread.Sleep(1000);
Thread.Sleep(1000);
}
private void CallOperationAsync()
{
foo dlgt = new foo (this.LongRunningMethod) ;
ArrayList inArrList = new ArrayList();
inArrList.Add(233);
ArrayList outArrList = new ArrayList();
// Create the callback delegate.
AsyncCallback asyncCallback = new AsyncCallback(MyAsyncCallback);
// Initiate the Asynchronous call passing in the callback delegate
// and the delegate object used to initiate the call.
IAsyncResult ar = dlgt.BeginInvoke("zorik", "zorik2", inArrList, out outArrList, asyncCallback, dlgt);
}
public void MyAsyncCallback(IAsyncResult ar)
{
string s ;
ArrayList outArrList;
// Because you passed your original delegate in the asyncState parameter
// of the Begin call, you can get it back here to complete the call.
foo dlgt = (foo) ar.AsyncState;
// Complete the call.
try
{
s = dlgt.EndInvoke(out outArrList, ar);
}
catch
{
}
}
private string LongRunningMethod(string param1, string param2, ArrayList list, out ArrayList outList)
{
Thread.Sleep(5000);
outList = new ArrayList();
outList.Add(8999);
list.Add(678);
// this control is inside update panel
txtAsync.Text = "Async";
updPnl1.Update();
return "Xrensuccess";
}
protected void Page_PreRender(object s, EventArgs e)
{
string a = "";
}
}