我正在開發一個應用程序,其中應用程序會向用戶提問一個問題,其中有幾個 - 例如詢問用戶是否要評估應用程序。我需要運行此方法,但它大大增加了應用程序啓動時間。我怎樣才能在後臺運行這個?我檢查了堆棧溢出的其他問題沒有太多的幫助。在後臺運行方法
簡稱爲::
checkUserStats();
方法:
private void checkUserStats()
{
// Load settings from IsolatedStorage first
try
{
userRemindedOfRating = Convert.ToBoolean(settings["userRemindedOfRating"].ToString());
}
catch (Exception)
{
userRemindedOfRating = false;
}
try
{
wantsAndroidApp = Convert.ToBoolean(settings["wantsAndroidApp"].ToString());
}
catch (Exception)
{
wantsAndroidApp = false;
}
//Check if the user has added more 3 notes, if so - remind the user to rate the app
if (mainListBox.Items.Count.Equals(4))
{
//Now check if the user has been reminded before
if (userRemindedOfRating.Equals(false))
{
//Ask the user if he/she wants to rate the app
var ratePrompt = new MessagePrompt
{
Title = "Hi!",
Message = "I See you've used the app a little now, would u consider doing a review in the store? It helps a lot! Thanks!:)"
};
ratePrompt.IsCancelVisible = true;
ratePrompt.Completed += ratePrompt_Completed;
ratePrompt.Show();
//Save the newly edited settings
try
{
settings.Add("userRemindedOfRating", true);
settings.Save();
}
catch (Exception)
{
}
//Update the in-memory boolean
userRemindedOfRating = true;
}
else if (userRemindedOfRating.Equals(true))
{
// Do nothing
}
}
else
{
}
// Ask the user if he/she would like an android app
if (wantsAndroidApp.Equals(false))
{
// We haven't asked the user yet, ask him/her
var androidPrompt = new MessagePrompt
{
Title = "Question about platforms",
Message = "Hi! I just wondered if you wanted to have this app for android? If so, please just send me a quick email. If enough people wants it, I'll create it:)"
};
androidPrompt.IsCancelVisible = true;
androidPrompt.Completed += androidPrompt_Completed;
androidPrompt.Show();
//Save the newly edited settings
try
{
settings.Add("wantsAndroidApp", true);
settings.Save();
}
catch (Exception)
{
}
//Update the in-memory boolean
wantsAndroidApp = true;
}
else if (wantsAndroidApp.Equals(true))
{
// We have asked the user already, do nothing
}
}
我現在嘗試這樣做:在後臺運行需要的方法
使用:
using System.ComponentModel;
聲明:
BackgroundWorker worker;
初始化:
worker = new BackgroundWorker();
worker.DoWork+=worker_DoWork;
方法:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
checkUserStats();
}
但它會導致System.UnauthorizedAccessException的:無效在我app.xaml.cs跨線程訪問
查看更新的問題請 – Erik
檢查答案編輯 –
這使我的一天!謝謝阿曼!:) – Erik