C#游戏中NPC的异步行为

9

这个问题与使用C# 5异步等待一些在多个游戏帧上执行的内容有关。

背景

当Miguel de Icaza首次在Alt-Dev-Conf 2012上展示C# 5异步框架用于游戏时,我非常喜欢使用asyncawait来处理游戏中的“脚本”(这么说是因为它们是用c#编写的,在我的情况下,即时编译但无论如何都是编译)。

即将发布的Paradox3D游戏引擎似乎也依赖于异步框架来处理脚本,但从我的角度来看,这种想法和实现之间存在真正的差距。

相关链接问题中,有人使用await让NPC执行一系列指令,而游戏的其余部分仍在运行。

想法

我希望更进一步,允许NPC同时执行多个动作,同时以顺序方式表达这些动作。类似于:

class NonPlayableCharacter 
{
    void Perform()
    {
        Task walking = Walk(destination); // Start walking
        Task sleeping = FallAsleep(1000); // Start sleeping but still walks
        Task speaking = Speak("I'm a sleepwalker"); // Start speaking
        await walking; // Wait till we stop moving.
        await sleeping; // Wait till we wake up.
        await speaking; // Wait till silence falls
    }
}

为了实现这一点,我使用了Jon Skeet的一篇非常精彩的答案,该答案来自于相关问题

实现

我的玩具实现由两个文件组成,NPC.cs和Game.cs。 NPC.cs:

using System;
using System.Threading.Tasks;

namespace asyncFramework
{
    public class NPC
    {
        public NPC (int id)
        {
            this.id = id;

        }

        public async void Perform ()
        {
                    Task babbling = Speak("I have a superpower...");
            await Speak ("\t\t\t...I can talk while talking!");
            await babbling; 
            done = true;
        }

        public bool Done { get { return done; } }

        protected async Task Speak (string message)
        {
            int previousLetters = 0;
            double letters = 0.0;
            while (letters < message.Length) {
                double ellapsedTime = await Game.Frame;
                letters += ellapsedTime * LETTERS_PER_MILLISECOND;
                if (letters - previousLetters > 1.0) {
                    System.Console.Out.WriteLine ("[" + this.id.ToString () + "]" + message.Substring (0, (int)Math.Floor (Math.Min (letters, message.Length))));
                    previousLetters = (int)Math.Floor (letters);
                }
            }
        }

        private int id;
        private bool done = false;
        private readonly double LETTERS_PER_MILLISECOND = 0.002 * Game.Rand.Next(1, 10);
    }
}

Game.cs:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace asyncFramework
{
    class Game
    {
        static public Random Rand { 
            get { return rand; }
        }

        static public Task<double> Frame {
            get { return frame.Task; }
        }

        public static void Update (double ellapsedTime)
        {
            TaskCompletionSource<double> previousFrame = frame; // save the previous "frame"
            frame = new TaskCompletionSource<double> (); // create the new one
            previousFrame.SetResult (ellapsedTime); // consume the old one
        }

        public static void Main (string[] args)
        {
            int NPC_NUMBER = 10; // number of NPCs 10 is ok, 10000 is ko
            DateTime currentTime = DateTime.Now; // Measure current time
            List<NPC> npcs = new List<NPC> (); // our list of npcs
            for (int i = 0; i < NPC_NUMBER; ++i) { 
                NPC npc = new NPC (i); // a new npc
                npcs.Add (npc); 
                npc.Perform (); // trigger the npc actions
            }
            while (true) { // main loop
                DateTime oldTime = currentTime;
                currentTime = DateTime.Now;
                double ellapsedMilliseconds = currentTime.Subtract(oldTime).TotalMilliseconds; // compute ellapsedmilliseconds
                bool allDone = true;
                Game.Update (ellapsedMilliseconds); // generate a new frame
                for (int i = 0; i < NPC_NUMBER; ++i) {
                    allDone &= npcs [i].Done; // if one NPC is not done, allDone is false
                }
                if (allDone) // leave the main loop when all are done.
                    break;
            }
            System.Console.Out.WriteLine ("That's all folks!"); // show after main loop
        }

        private static TaskCompletionSource<double> frame = new TaskCompletionSource<double> ();
        private static Random rand = new Random ();
    }
}

这是一个非常直接的实现!

问题

然而,它似乎没有按预期工作。

更准确地说,当NPC_NUMBER为10、100或1000时,我没有问题。但在10,000或以上时,程序不再完成,它会写出“speaking”的行一段时间,然后控制台上就没有其他内容了。 虽然我不打算在我的游戏中同时拥有10,000个NPC,但它们也不会写出愚蠢的对话,而是会移动、动画、加载纹理等等。因此,我想知道我的实现有什么问题,如果有任何修复的机会。

我必须说明的是,代码正在Mono下运行。此外,“有问题”的值可能在您的位置不同,可能是计算机特定的问题。如果问题似乎无法在.Net下重现,我将尝试在Windows下运行它。

编辑

在.Net中,它可以运行到1000000,尽管需要时间进行初始化,它可能是Mono特有的问题。 调试数据告诉我确实有未完成的NPC。不幸的是,还没有关于原因的信息。

编辑2

在Monodevelop下,无调试器启动应用程序似乎可以解决问题。然而,为什么能解决问题我不知道…
结尾
我意识到这是一个非常冗长的问题,我希望你能花时间阅读它,我真的很想了解我做错了什么。
非常感谢您的帮助。

2
我认为你应该尝试在非Mono实现上进行比较,以排除基于平台的问题。 - Dave Swersky
等Windows重启完成后,我会立即处理。 - dureuill
1
即使在调试模式下,这种情况也会发生吗? - Jon Senchyna
发布和调试都没有改变任何东西。然而,在Monodevelop中不使用调试运行(CTRL+F5)似乎可以解决问题。 - dureuill
allDone是false,因为有几个NPC的“done”为false。 - dureuill
显示剩余8条评论
2个回答

2
关于TaskCompletionSource.SetResult有一个重要的点:由SetResult触发的继续回调通常是同步的
对于没有在其主线程上安装同步上下文对象的单线程应用程序(例如您的应用程序),这一点尤为真实。我无法在您的示例应用程序中发现任何真正的异步性,也就是说,任何会导致线程切换的东西,例如await Task.Delay()。基本上,您使用TaskCompletionSource.SetResult类似于同步地触发游戏循环事件(这些事件使用await Game.Frame处理)。 SetResult可能(通常)会同步完成这一事实经常被忽视,但它可能会导致隐式递归、堆栈溢出和死锁。如果您感兴趣,我刚好回答了一个相关问题,其中包含更多详细信息。
话虽如此,我也没有在您的应用程序中发现任何递归。很难说什么让Mono困惑了。为了进行实验,请尝试定期进行垃圾回收,看看是否有帮助:
Game.Update(ellapsedMilliseconds); // generate a new frame
GC.Collect(0, GCCollectionMode.Optimized, true);

更新,尝试在此介绍实际的并发性并查看是否有所改变。最简单的方法是将 Speak 方法更改为以下内容(请注意 await Task.Yield()):
protected async Task Speak(string message)
{
    int previousLetters = 0;
    double letters = 0.0;
    while (letters < message.Length)
    {
        double ellapsedTime = await Game.Frame;

        await Task.Yield();
        Console.WriteLine("Speak on thread:  " + System.Threading.Thread.CurrentThread.ManagedThreadId);

        letters += ellapsedTime * LETTERS_PER_MILLISECOND;
        if (letters - previousLetters > 1.0)
        {
            System.Console.Out.WriteLine("[" + this.id.ToString() + "]" + message.Substring(0, (int)Math.Floor(Math.Min(letters, message.Length))));
            previousLetters = (int)Math.Floor(letters);
        }
    }
}

抱歉,没有定期垃圾回收的帮助! - dureuill
@dureuill,我建议你向Xamarin报告这个bug。不过,请查看我的更新,关于引入并发性的内容。 - noseratio - open to work
非常晚的回答,但我尝试了您关于引入并发性的更新。在运行一段时间后,它会在Speak方法结束时引发一个System.InvalidOperationException,并显示消息“任务已经完成”。此时,由于只有在调试器中运行才会遇到此错误,我认为我能做的最好的事情就是向Xamarin报告。 - dureuill

1

我不确定这是否相关,但是这一行引起了我的注意:

allDone &= npcs [i].Done; // if one NPC is not done, allDone is false

我建议等待你的Perform方法。由于你希望所有NPC都异步运行,将它们的Perform Task添加到列表中,并使用Task.WaitAll(...)进行完成。
反过来,你可以这样做:
var scriptList = new List<Task>(npcs.Count);

for (int i = 0; i < NPC_NUMBER; ++i) 
{
  var scriptTask = npcs[i].Perform();
  scriptList.Add(scriptTask);

  scriptTask.Start();
}

Task.WaitAll(scriptList.ToArray());

只是提供一些思路。

我已经使用了Mono Task库的await/async关键字,没有任何问题,所以我不会轻易归咎于Mono。


我并不指责任何事情,我喜欢Mono。我只是尝试两个平台以确保问题与平台无关。我会马上测试你的答案。 - dureuill
@SiLo,在@dureuill的代码中,所有NPC都是同步运行的,它是单线程的(更多细节)。执行Task.WaitAll(scriptList)只会导致死锁。 - noseratio - open to work

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接