我意识到OnStart()只是一个事件,所以我知道让它返回void是没有问题的。但是我仍然收到令人讨厌的消息,给我警告
有没有一种方法可以让我在OnStart()中运行异步方法?
我可以做些类似的事情来创建一个Task并使它们(或当前在OnStart中的所有代码)在该任务中运行吗?还是可以使用_ =构造忽略在OnStart内部运行的Task的输出?
更新:
根据Nikosi的建议,这是我正在考虑做的事情:
应用
public partial class App : Application
{
public async Task CheckLatestVersion()
{
try
{
var isLatest = await CrossLatestVersion.Current.IsUsingLatestVersion();
if (!isLatest)
{
var update = await MainPage.DisplayAlert("New Version", $"\nThere is a new version of this app available.\n\nWould you like to update now?\n", "Yes", "No");
if (update)
{
await CrossLatestVersion.Current.OpenAppInStore();
}
}
}
catch (Exception ex)
{
var ignore = ex;
}
}
private event EventHandler started = delegate { };
protected override void OnStart() {
this.started += onStarted; //Subscribe to event
started(this, EventArgs.Empty); //Raise event
}
protected async void onStarted(object sender, EventArgs args)
{
try
{
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
if (Settings.Rev == REV.No && (new[] { 15, 30, 50 }).Contains(Settings.Trk2))
{
await ReviewAppAsync(Settings.Trk2);
}
if (App.devIsPhysical && (new[] { 10, 20, 30 }).Contains(Settings.Trk2))
{
await CheckLatestVersion();
}
// This
await Helper.PopulateMetrics();
// Or this
_ = Helper.PopulateMetrics();
await Helper.LogStart();
}
}
catch(Exception)
{
;
}
this.started -= onStarted; //Unsubscribe (OPTIONAL but advised)
}
}
助手
public static async Task PopulateMetrics()
{
await Task.Run(() =>
{
if (App.CPUSpeed == 0)
{
var stopWatch = Stopwatch.StartNew();
stopWatch.Start();
ArrayList al = new ArrayList(); for (int i = 0; i < 5000000; i++) al.Add("hello");
App.CPUSpeed = 20000 / stopWatch.ElapsedMilliseconds;
}
});
}
public async Task ReviewAppAsync(int count)
{
try
{
async Task<bool> DelayAndDisplayAlert()
{
await Task.Delay(60000);
return await MainPage.DisplayAlert("Review", $"\nWe noticed that you've used this application {count} times. We'd love to get some feedback for the application.\n\nCan you help us by rating the application or leaving a review?\n", "Yes", "No");
}
if (count == 0 || await DelayAndDisplayAlert())
{
if (Plugin.StoreReview.CrossStoreReview.IsSupported)
{
if (Xamarin.Forms.Device.RuntimePlatform == "iOS")
Plugin.StoreReview.CrossStoreReview.Current.OpenStoreReviewPage("1477984412");
else if (Xamarin.Forms.Device.RuntimePlatform == "Android")
Plugin.StoreReview.CrossStoreReview.Current.OpenStoreReviewPage("com.ankiplus.Japanese");
}
}
}
catch (Exception ex)
{
Helper.RegisterCrash(ex,
new Dictionary<string, string> {
{"ReviewAppAsync", "Exception" },
{"Device Model", DeviceInfo.Model },
{"Exception", ex.ToString()}
});
}
}
答案 0 :(得分:2)
OnStart
实际上不是事件处理程序。这与框架的构建方式有关。但是,您可以创建一个事件和异步处理程序,以使异步代码能够按预期等待。
private event EventHandler started = delegate { };
protected override void OnStart() {
this.started += onStarted; //Subscribe to event
started(this, EventArgs.Empty); //Raise event
}
protected async void onStarted(object sender, EventArgs args) {
try {
//await custom code here
} catch {
//handle errors
}
//this.started -= onStarted; //Unsubscribe (OPTIONAL but advised)
}
异步事件处理程序是允许async void
并可以正确处理的一个例外。
将async void
与被覆盖的非事件处理程序OnStart
一起使用将导致遇到的任何异常都被吞没,因为非事件处理程序上的async void
被触发并忘记了。