在 .NET 中,使用 C# 是否可以在没有多线程的情况下实现基于事件的异步模式?

在 .NET 中,使用 C# 是否可以在没有多线程的情况下实现基于事件的异步模式?

问题描述:

我对 Node.js 的架构设计感到惊讶,想知道 C#有能力做这样的设计:

I am amazed by the architectural design of Node.js and was wondering if C# is capable of such a design:

异步、基于事件/事件循环、非阻塞I/O,无需多线程.

Asynchronous, event based / event loop, non-blocking I/O without multithreading.

我认为所有实现标准异步编程模型的 BeginXyz 操作都在线程池线程上运行回调,这使得应用程序自动多线程.

I think that all the BeginXyz operations that implement the standard asynchronous programming model run the callback on a thread pool thread, which makes the application automatically multi-threaded.

但是,您可以通过使用 Control.Invoke 或更一般地 SynchronizationContext.

However, you can achieve single-threaded asynchronous programming model by synchronizing all the operations through the single GUI thread that is maintained for windows applications using Control.Invoke or more generally, SynchronizationContext.

BeginXyz 的每次调用都必须按照以下方式重写:

Each call to BeginXyz would have to be rewritten along these lines:

// Start asynchronous operation here (1)
var originalContext = SynchronizationContext.Current;
obj.BeginFoo(ar =>
  // Switch to the original thread
  originalContext.Post(ignored => {
    var res = obj.EndFoo(); 
    // Continue here (2)
  }));

标记为 (2) 的代码将继续在与 (1) 中的代码相同的线程上运行,因此您将仅使用线程池线程将回发转发回原始(单个)线程.

The code marked as (2) will continue running on the same thread as the code in (1), so you'll use the thread-pool thread only for forwarding the postback back to the original (single) thread.

作为旁注,F# 中的异步工作流更直接地支持这一点,并且它可以用于非常优雅的 GUI 编程风格 如此处所述.我不知道 node.js,但我想您可能也会对 F# 异步工作流 感到惊讶,因为它们对于异步/基于事件/...编程风格:-)

As a side-note, this is more directly supported by asynchronous workflows in F# and it can be used for quite elegant style of GUI programming as described here. I don't know node.js, but I suppose that you may be also amazed by F# asynchronous workflows as they are really cool for asynchronous/event based/... style of programming :-)