I have one new problem. I want to do some operations with the response, but I get a NullReferenceException, because it isn't arrived yet... Here is my code:
public partial class MainPage : PhoneApplicationPage
{
public static string res = null;
// Constructor
public MainPage()
{
InitializeComponent();
string Url = "http://twitter.com";
WebRequest req = WebRequest.Create(Url);
req.BeginGetResponse(new AsyncCallback(request_CallBack), req);
int i = MainPage.res.Length; // NullReferenceException
}
void request_CallBack(IAsyncResult result)
{
WebRequest webRequest = result.AsyncState as WebRequest;
WebResponse response = (WebResponse)webRequest.EndGetResponse(result);
Stream baseStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(baseStream))
{
res = reader.ReadToEnd();
Dispatcher.BeginInvoke(() => { MessageBox.Show("The response is arrived."); });
Dispatcher.BeginInvoke(() => { tbResponse.Text = res; });
}
}
}
But when I use the ManualResetEvent class, my app is just hanging, because of the if(dataReady.WaitOne()) line. Here is the complete code with the ManualResetEvent class:
public partial class MainPage : PhoneApplicationPage
{
public static string res = null;
ManualResetEvent dataReady;
// Constructor
public MainPage()
{
InitializeComponent();
string Url = "http://twitter.com";
dataReady = new ManualResetEvent(false);
WebRequest req = WebRequest.Create(Url);
req.BeginGetResponse(new AsyncCallback(request_CallBack), req);
if (dataReady.WaitOne())
{
int i = MainPage.res.Length;
}
}
void request_CallBack(IAsyncResult result)
{
WebRequest webRequest = result.AsyncState as WebRequest;
WebResponse response = (WebResponse)webRequest.EndGetResponse(result);
Stream baseStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(baseStream))
{
res = reader.ReadToEnd();
Dispatcher.BeginInvoke(() => { MessageBox.Show("The response is arrived."); });
Dispatcher.BeginInvoke(() => { tbResponse.Text = res; });
}
dataReady.Set();
}
}
So, there is my question: How can I wait the response and do operations with it? (I tried to use the Application.DoEvent method, but it isn't exist in WP7...)