【发布时间】:2020-02-22 12:59:23
【问题描述】:
我意识到 OnStart() 只是一个事件,所以我知道让它返回 void 没有问题。但是,我仍然收到令人讨厌的消息,给我一个警告
是否有替代方法允许我在 OnStart() 中运行异步方法?
我可以做一些事情,比如创建一个任务并让它们(或我当前在 OnStart 中的所有代码)在该任务中运行吗?或者我可以使用 _ = 构造来忽略在 OnStart 中运行的任务的输出吗?
更新:
根据 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()}
});
}
}
【问题讨论】:
标签: c# xamarin xamarin.forms