我有一个主页面,可以从网络上获取新闻和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 =时,它会显示消息框。
目标:
目的是在后台下载联系人数据,以便没有太多时间等待联系人页面...换句话说,在联系人页面打开之前开始获取联系人数据。
但是代码没有HandleResponseContacts,当我导航到另一页时,它只是没有输入该功能。
答案 0 :(得分:0)
找到我错的地方。
错误的方法是让联系人页面上的主线程忙碌:
我应该这样做:
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");
在后台工作人员中。
代码无效,因为主线程正忙。