【发布时间】:2014-06-07 17:33:54
【问题描述】:
在我的游戏中,我注意到有些卡顿,因为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 我可以添加哪些信息?
-
当然是从分析器得到的结果。
-
您的问题范围之外的一些cmets:1)不要使用
async void(事件处理程序除外),如果它不返回任何结果,请使用async Task。 2) 你没有理由使用Task.Factory.StartNew。只需await UpdateAdsMethod。 -
@Aron "async != multithreading" 在 async 和 Task 领域是
标签: c# silverlight asynchronous xna task