是否有可能在.NET中,使用C#,实现基于事件的异步模式没有多线程? [英] Is it possible in .NET, using C#, to achieve event based asynchronous pattern without multithreading?

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

问题描述

我对 Node.js的的建筑设计赞叹不已,并想知道如果C#能够这样设计的:


  

异步,根据事件/事件循环,无阻塞 I / O 没有多线程



解决方案

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

不过,您可以通过正在使用维护Windows应用程序的单一GUI线程同步所有的操作实现单线程的异步编程模型 Control.Invoke 或更普遍,的SynchronizationContext

BeginXyz 每次调用都必须沿着这些线路改写:

  //此处开始异步操作(1)
VAR originalContext = SynchronizationContext.Current;
obj.BeginFoo(AR =>
  //切换到原来的线程
  originalContext.Post(忽略=> {
    VAR解析度= obj.EndFoo();
    //继续在这里(2)
  }));

在code标记为(2)将继续同一个线程在code上运行(1),因此,您使用线程池线程只转发回发回原来的(单)线程。

作为一个侧面说明,这是更直接在F#异步工作流的支持,它可用于GUI编程<一个相当优雅的风格href=\"http://dotnetslackers.com/articles/net/Programming-user-interfaces-using-f-sharp-workflows.aspx\">as这里描述。我不知道的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 :-)

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

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