1

我正在尝试使用 C# 的新await功能实现 NPC 脚本。这是我的概念证明。

NPC.cs你可以看到这个片段:

public async void Run(INPC npc)
{
    npc.Say("Hello!");
    await npc.WaitForOk();
    npc.Say("This is an example of some weird crap.");
    await npc.WaitForOk();
    npc.Say("Bye.");
    await npc.WaitForOk();
}

在一个真实的例子中,该脚本将使用 IronPython 之类的脚本语言来实现。即使它将来可能支持async/await关键字,但每次调用都必须这样做非常麻烦和烦人。

我尝试让另一种方法异步并执行等待,并让脚本简单地调用它,但由于方式async/await工作方式,脚本方法(Run)将简单地继续而不会暂停/阻塞。

有没有办法避免必须使脚本方法异步并且必须await在每次调用之前使用,同时仍然保留类似协程的功能?

此外,如果有比使用async/await同时仍然具有线程效率的更好的解决方案,请突出显示它。

谢谢!

4

2 回答 2

1

That's a very interesting use for async/await.

I've compiled a lot of syntax-related questions from around the web into one of my blog posts. In short, there are good reasons why async and await are both required.

If you're willing to add state to your NPCs, consider using an observer-based approach (Rx). This approach is capable of complex interactions, and could also allow parallel execution of different NPCs.

You could also pattern your NPCs on threadpool tasks, which are pretty efficient - when they block, the CPU is made available for other tasks.

于 2011-12-29T18:52:03.850 回答
1

我不知道你为什么要这么努力地避免await。我认为对这种代码要求它是一个好主意,因为很难说出代码实际上做了什么。所以,我的观点是,使用await这种方式可能是你最好的选择。

此外,如果可以的话,最好避免async void使用方法,因为您无法捕获它们抛出的异常。

我可以想象有一些方法可以避免写作async,比如:

npc.AddAction(n => n.Say("Hello!"))
   .AddAction(n => n.WaitForOk())
   .AddAction(n => n.Say("This is an example of some weird crap."))
   .AddAction(n => n.WaitForOk());

npc.Run();

在这里,Run()处理使用构建的操作列表,AddAction()await在必要时使用。

但我怀疑您是否可以像使用awaits 的代码一样简单。(此外,在这样的代码中实现任何类型的控制流都会使它变得非常不可读。)

于 2011-12-30T12:20:40.800 回答