当我的应用程序启动时,我想显示启动画面并创建 httpwebrequest,当请求完成时,隐藏启动画面并显示主页。
这是我的启动画面:
private void ShowPopup()
{
this.popup = new Popup();
this.popup.Child = new PopupSplash();
this.popup.IsOpen = true;
StartLoadingData();
}
private void StartLoadingData()
{
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync();
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
this.popup.IsOpen = false;
}
);
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
using (var db = new ListDataContext(ListDataContext.DBConnectionString))
{
if (!db.DatabaseExists())
{
db.CreateDatabase();
}
}
Thread.Sleep(4000);
}
这是我的httpwebrequest:
private void main_WebResponseAvailableEventHandler(object sender, string response, string url)
{
SearchResult result = new SearchResult(response, url);
PhoneApplicationService.Current.State["result"] = result;
this.NavigationService.Navigate(new Uri("/SearchPivotPage.xaml", UriKind.Relative));
}
private void HandleWebResponse(IAsyncResult asyncResult)
{
WebRequestState state = (WebRequestState)asyncResult.AsyncState;
HttpWebRequest request = state.Request;
string url = request.RequestUri.ToString();
state.Response = (HttpWebResponse)request.EndGetResponse(asyncResult);
if (state.Response != null)
{
StreamReader reader = new StreamReader(state.Response.GetResponseStream());
StringBuilder sb = new StringBuilder();
while (!reader.EndOfStream)
sb.Append(reader.ReadLine());
string text = sb.ToString();
Dispatcher.BeginInvoke(() =>
{
if (WebResponseAvailable != null)
{
WebResponseAvailable(this, text, url);
}
});
}
}
在构造函数 MainPage()
....
ShowPopup();
HttpWebRequest movieRequest = (HttpWebRequest)WebRequest.Create(url);
WebRequestState state = new WebRequestState();
state.Request = movieRequest;
movieRequest.BeginGetResponse(new AsyncCallback(HandleWebResponse), state);
WebResponseAvailable += main_WebResponseAvailableEventHandler;
....
有没有办法我可以做我想做的事?或者两者都在其他线程中这是不可能的?