我有一个主页,它从网络其他信息中获取新闻和 n 后台加载:
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(GetContacts);
bw.RunWorkerAsync();
private void GetContacts(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(getServiceContactData);
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
long cont = 0;
//This made to pause a thread for a long time
do
{
cont++;
}
while (cont != 999999999);
getServiceContactData();
}
private void getServiceContactData()
{
HttpWebRequest request = HttpWebRequest.CreateHttp(GS.BACKEND_HOST + "sfbsfb");
request.BeginGetResponse(new AsyncCallback(HandleResponseContacts), request);
}
private void HandleResponseContacts(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
using (WebResponse response = request.EndGetResponse(result))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string JSON = reader.ReadToEnd();
if (JSON == "")
{
NoItems = true;
}
IsolatedStorage IS = new IsolatedStorage();
IS.Save("ContactsStorage.txt", JSON);
IS.SaveContactsRetrieveDate(DateTime.Now.ToString("dd.MM.yyyy"));
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//MessageBox.Show("got");
});
}
}
}
}
在联系人页面上有:
string contactsRetriveDate = "";
DateTime a;
string now = DateTime.Now.ToString("MM/dd/yyyy");
string then = "";
do
{
contactsRetriveDate = IS.ReadContactsRetriveDate();
if (contactsRetriveDate != "")
{
a = DateTime.ParseExact(contactsRetriveDate, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
a.ToString("MM/dd/yyyy");
}
}
while(then!=now);
MessageBox.Show("Estj");
此代码检查联系人的最后更新日期,当 now = then 时显示消息框。
目的:
目的是在后台下载联系人数据,以便在联系人页面上没有太多时间等待......换句话说,在打开联系人页面之前开始获取联系人数据。
但是代码不做HandleResponseContacts,当我导航到另一个页面时它只是不进入那个函数。