使用C#可以在.NET中实现基于事件的异步模式,而不需要多线程吗? [英] Is it possible in .NET, using C#, to achieve event based asynchronous pattern without multithreading?

查看:148
本文介绍了使用C#可以在.NET中实现基于事件的异步模式,而不需要多线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶于 Node.js 的架构设计,并且想知道如果C#可以这样设计:


异步,基于事件的事件循环,非阻塞


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



但是,您可以通过单个GUI线程同步所有操作来实现单线程异步编程模型,该线程使用 Control.Invoke 或更一般地, SynchronizationContext



每个通话到 BeginXyz 会必须重写这些行:

  //这里开始异步操作(1)
var originalContext = SynchronizationContext。当前;
obj.BeginFoo(ar =>
//切换到原始线程
originalContext.Post(ignored => {
var res = obj.EndFoo();
//继续这里(2)
}));

标记为(2)的代码将继续在与(1)中的代码相同的线程上运行, ,所以你将使用线程池线程将回发转发回原来的(单)线程。



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


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

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

解决方案

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.

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.

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)
  }));

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.

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 :-)

这篇关于使用C#可以在.NET中实现基于事件的异步模式,而不需要多线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆