c# - C# 游戏中 NPC 的异步行为

标签 c# .net asynchronous mono c#-5.0

这个问题与this one (Using C# 5 async to wait for something that executes over a number of game frames)有关.

上下文

当 Miguel de Icaza 在 Alt-Dev-Conf 2012 首次展示游戏的 C# 5 异步框架时,我真的很喜欢使用 asyncawait 来处理“脚本”的想法(可以这么说,因为它们是在 c# 中,在我的例子中,编译---及时但无论如何编译)在游戏中。

即将到来 Paradox3D游戏引擎好像rely on the async framework也可以处理脚本,但从我的角度来看,想法与实现之间存在真正的差距。

linked related question ,有人使用 await 让 NPC 执行一系列指令,而游戏的其余部分仍在运行。

想法

我想更进一步,允许 NPC 同时执行多个 Action ,同时按顺序表达这些 Action 。 类似的东西:

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 的 as-wonderful-as-ever answer来自 related question .

实现

我的玩具实现包含两个文件,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);
    }
}

游戏.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 或以上时,程序不再完成,它会写“说话”行一段时间,然后控制台上就什么也没有了。 虽然我没有考虑在我的游戏中同时拥有 10,000 个 NPC,但他们也不会编写愚蠢的对话框,还会移动、动画、加载纹理等。所以我想知道我的实现有什么问题,以及我是否有机会修复它。

我必须明确代码是在 Mono 下运行的。此外,“有问题的”值在您所在的地方可能会有所不同,它可能是计算机特定的东西。如果问题在.Net下似乎无法重现,我会在Windows下尝试。

编辑

在 .Net 中,它运行到 1000000,虽然它需要时间来初始化,但它可能是 Mono 特定的问题。 调试器数据告诉我,确实有 NPC 没有完成。遗憾的是,目前还没有关于原因的信息。

编辑2

在 Monodevelop 下,在没有调试器的情况下启动应用程序似乎可以解决问题。不知道为什么...

结束词

我意识到这是一个非常非常冗长的问题,希望您能花时间阅读它,我真的很想了解我做错了什么。

非常感谢您。

最佳答案

TaskCompletionSource.SetResult 有一点很重要:SetResult 触发的延续回调通常是同步

对于主线程上没有安装同步上下文对象的单线程应用程序尤其如此,就像您的应用程序一样。我无法在您的示例应用程序中发现任何真正的异步性,任何会导致线程切换的东西,例如等待 Task.Delay()。本质上,您对 TaskCompletionSource.SetResult 的使用类似于同步触发游戏循环事件(使用 await Game.Frame 处理)。

SetResult 可能(通常确实)同步完成这一事实经常被忽视,但它可能会导致隐式递归、堆栈溢出和死锁。我只是碰巧回答了一个 related question ,如果您对更多详细信息感兴趣。

也就是说,我也无法在您的应用程序中发现任何递归。在这里很难说出是什么让 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);
        }
    }
}

关于c# - C# 游戏中 NPC 的异步行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21863007/

相关文章:

.net - 如何将 DBQuery<T> 转换为 ObjectQuery<T>?

node.js - Nodejs事件循环,如何正确使用nextTick

C# 从异步任务返回不起作用

c# - “An explicit conversion exists”-LINQ

c# - 如何在 XAML 中定义对现有对象的引用?

c# - 将列表分成 3 部分以加速异步功能

c# - Type.GetType(string) 应该知道动态生成的类型吗?

c# - 将 PCL 代码传递/解析到 word 或 excel

c# - MenuItem 背景不透明度而不是其文本?

java - 使 RxJava 运算符链并发