在我的游戏中,我注意到一些冻结,因为AdComponent
试图从互联网上下载一个新的广告来绘制在我的游戏中。我的方法是异步运行吗?
如何冻结功能被初始化:
// Declarations
DrawableAd drawableAd;
// Inside constructor of my game class
AdComponent.Initialize("MyAppId");
Rectangle rect = new Rectangle(0, resolution_h_ - 50, 320, 50);
drawableAd_ = AdComponent.Current.CreateAd("AdId", rect, false); // false is to set AutoRefresh of the ad
为了使广告点击和下载它,我在每一个更新步骤打电话:AdComponent.Current.Update(e_.ElapsedTime);
的问题是如果我同时调用它,则会使我的游戏在下载新广告时冻结一段时间:
private void OnUpdate(object sender, GameTimerEventArgs e)
{
// ... GameUpdates
AdComponent.Current.Update(e.ElapsedTime);
}
所以,我虽然解决的办法是把AdComponent.Current.Update(e.ElapsedTime);
放在后台线程上,用“低优先级”来解决冻结问题。所以我做:
private async void UpdateAds()
{
if (ad_update_completed_)
await Task.Factory.StartNew(() => UpdateAdsMethod());
}
private async Task UpdateAdsMethod()
{
ad_update_completed_ = false;
AdComponent.Current.Update(e_.ElapsedTime);
ad_update_completed_ = true;
}
private void OnUpdate(object sender, GameTimerEventArgs e)
{
// ... GameUpdates
e_ = e;
UpdateAds();
}
这一点,我发现后(不使用分析器),大部分的冻结(不是全部)的地方去了。但是我有一些疑问,因为编译器发出一个警告,说UpdateAdsMethod();
将被同步执行。
我在做什么错?
异步!=多线程。没有足够的信息来帮助优化你的代码。 – Aron
@Aron我可以添加什么信息? –
从分析器获得的结果当然。 –