我不确定 async/await 是否对此有好处,但这绝对是可能的。我创建了一个小型(好吧,至少我试图使其尽可能小)测试环境来说明可能的方法。让我们从一个概念开始:
/// <summary>A simple frame-based game engine.</summary>
interface IGameEngine
{
/// <summary>Proceed to next frame.</summary>
void NextFrame();
/// <summary>Await this to schedule action.</summary>
/// <param name="framesToWait">Number of frames to wait.</param>
/// <returns>Awaitable task.</returns>
Task Wait(int framesToWait);
}
这应该允许我们以这种方式编写复杂的游戏脚本:
static class Scripts
{
public static async void AttackPlayer(IGameEngine g)
{
await g.Wait(60);
while(true)
{
await DoSomeLogic(g);
await g.Wait(30);
}
}
private static async Task DoSomeLogic(IGameEngine g)
{
SomethingHappening();
await g.Wait(10);
SomethingElseHappens();
}
private static void ShootAtPlayer()
{
Console.WriteLine("Pew Pew!");
}
private static void SomethingHappening()
{
Console.WriteLine("Something happening!");
}
private static void SomethingElseHappens()
{
Console.WriteLine("SomethingElseHappens!");
}
}
我将以这种方式使用引擎:
static void Main(string[] args)
{
IGameEngine engine = new GameEngine();
Scripts.AttackPlayer(engine);
while(true)
{
engine.NextFrame();
Thread.Sleep(100);
}
}
现在我们可以进入实现部分。当然你可以实现一个自定义的等待对象,但我只依赖Task
and TaskCompletionSource<T>
(不幸的是,没有非通用版本,所以我只使用TaskCompletionSource<object>
):
class GameEngine : IGameEngine
{
private int _frameCounter;
private Dictionary<int, TaskCompletionSource<object>> _scheduledActions;
public GameEngine()
{
_scheduledActions = new Dictionary<int, TaskCompletionSource<object>>();
}
public void NextFrame()
{
if(_frameCounter == int.MaxValue)
{
_frameCounter = 0;
}
else
{
++_frameCounter;
}
TaskCompletionSource<object> completionSource;
if(_scheduledActions.TryGetValue(_frameCounter, out completionSource))
{
Console.WriteLine("{0}: Current frame: {1}",
Thread.CurrentThread.ManagedThreadId, _frameCounter);
_scheduledActions.Remove(_frameCounter);
completionSource.SetResult(null);
}
else
{
Console.WriteLine("{0}: Current frame: {1}, no events.",
Thread.CurrentThread.ManagedThreadId, _frameCounter);
}
}
public Task Wait(int framesToWait)
{
if(framesToWait < 0)
{
throw new ArgumentOutOfRangeException("framesToWait", "Should be non-negative.");
}
if(framesToWait == 0)
{
return Task.FromResult<object>(null);
}
long scheduledFrame = (long)_frameCounter + (long)framesToWait;
if(scheduledFrame > int.MaxValue)
{
scheduledFrame -= int.MaxValue;
}
TaskCompletionSource<object> completionSource;
if(!_scheduledActions.TryGetValue((int)scheduledFrame, out completionSource))
{
completionSource = new TaskCompletionSource<object>();
_scheduledActions.Add((int)scheduledFrame, completionSource);
}
return completionSource.Task;
}
}
主要观点:
Wait
方法创建一个任务,该任务在达到指定帧时完成。
- 我保留了预定任务的字典,并在达到所需的帧后立即完成它们。
更新:通过删除不必要的简化代码List<>
。