开发者

How do I make my function wait until an async function has completed?

I need some code to allow me to know when an async thread has completed. This is for my Windows phone app I'm making. The app is a bus tracker to show live departures and data will be taken from online web page.

I have this line of code in my GetDataFeed function

 // start the asynchronous request
IAsyncResult aResult =   BusStopFeedRequest.BeginGetResponse(new AsyncCallback(HandleFeedData), myState);

This 开发者_如何学JAVAwill fire off my HandleFeedData function that will save a websites source code into a text string variable.

My problem is the textbox on my phone app wont populate the content of the string as there is no data in string just yet. This is called by textbox1.Text = obj.GetText() which should be returning the private string in my instantiated class.

I have looked into using the aResult.AsyncWaitHandle.WaitOne() and tried polling for the aResult.IsCompleted() methods but from what I read and found myself, these just dont work. The WaitOne throws an unexpected error and the polling of IsCompleted is in an never ending loop.

Has any one got any insights into what I can do to allow my function to wait for the async request to complete so it updates my class variable so my textbox can then see the data


Are you certain that the string is actually being downloaded? "BeginGetResponse" is a function on the WebRequest class, which is not available on windows phone. It's possible that the data is not being downloaded. However, if it is being downloaded, I suggest you do something like this:

IAsyncResult aResult = BusStopFeedRequest.BeginGetResponse(new AsyncCallback(HandleFeedData));

and then:

private void HandleFeedData(IAsyncResult result)
{
    string feedData = (string)result.AsyncState;
    textbox1.Text = feedData;
    // code to save the feedData here
}

However, it would be helpful to know exactly when BusStopFeedRequest's "BeginGetResponse" is fired.


In the windows phone, HTTPWebRequest contain BeginGetResponse and EndGetResponse method. You need to add similar code on the function HanldeFeedData function.

HttpWebResponse response=(result.AsyncState as HttpWebrequest).EndGetResponse(result) as HttpWebResponse;
 string returnValue=null;
  using (StreamReader sr=new StreamReader(response.GetResponseStrem())
  {
      returnValue=sr.ReadToEnd();
   } 

   Dispatcher.BeginInvoke(new Action(()=>textbox1.Text=returnValue));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜