從我的WPF應用程序調用Web服務時遇到了很大的問題。應用程序/窗口鎖定,直到過程完成。我試圖異步運行,但問題仍然存在。當調用webservice時,WPF窗口被鎖定。即使在異步運行時
目前,我所做的Web服務調用可以持續45-60秒。它在服務器上運行一個進程來獲取大量數據。由於需要一段時間,我希望有一個進度條不斷移動,以便用戶看到應用程序沒有停滯或任何事情(您知道他們有多不耐煩)。
所以:
private void btnSelect_Click(object sender, RoutedEventArgs e)
{
wDrawingList = new WindowDrawingList(systemManager);
AsyncMethodHandler caller = default(AsyncMethodHandler);
caller = new AsyncMethodHandler(setupDrawingList);
// open new thread with callback method
caller.BeginInvoke((Guid)((Button)sender).Tag, MyAsyncCallback, null);
}
點擊一個按鈕,該應用程序將創建形式異步的東西將被張貼到,併成立了異步調用的東西的異步方法。
public bool setupDrawingList(Guid ID)
{
if (systemManager.set(ID))
{
wDrawingList.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
{
wDrawingList.ShowForm();
Hide();
}));
return true;
}
return false;
}
這是異步方法。 showForm方法包含設置新表單的呼叫,包括怪物網絡服務呼叫
public void MyAsyncCallback(IAsyncResult ar)
{
// Because you passed your original delegate in the asyncState parameter of the Begin call, you can get it back here to complete the call.
MethodDelegate dlgt = (MethodDelegate)ar.AsyncState;
// Complete the call.
bool output = dlgt.EndInvoke(ar);
try
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult)ar;
AsyncMethodHandler caller = (AsyncMethodHandler)result.AsyncDelegate;
// Because this method is running from secondary thread it can never access ui objects because they are created
// on the primary thread.
// Call EndInvoke to retrieve the results.
bool returnValue = caller.EndInvoke(ar);
// Still on secondary thread, must update ui on primary thread
UpdateUI(returnValue == true ? "Success" : "Failed");
}
catch (Exception ex)
{
string exMessage = null;
exMessage = "Error: " + ex.Message;
UpdateUI(exMessage);
}
}
public void UpdateUI(string outputValue)
{
// Get back to primary thread to update ui
UpdateUIHandler uiHandler = new UpdateUIHandler(UpdateUIIndicators);
string results = outputValue;
// Run new thread off Dispatched (primary thread)
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, uiHandler, results);
}
public void UpdateUIIndicators(string outputValue)
{
// update user interface controls from primary UI thread
sbi3.Content = "Processing Completed.";
}
任何幫助或理論的讚賞。我很茫然。
在此先感謝
原來你解決得比我輸入的速度快。好一個。 – 2010-05-17 13:06:30