C# 多线程与异步操作实现的探讨

    技术2022-05-20  41

    原文链接:http://dev.firnow.com/course/4_webprogram/asp.net/netjs/2008530/118075.html

     

    随着拥有多个硬线程CPU(超线程、双核)的普及,多线程和异步操作等并发程序设计方法也受到了更多的关注和讨论。本文主要是想与园中各位高手一同探讨一下如何使用并发来最大化程序的性能。  多线程和异步操作的异同  多线程和异步操作两者都可以达到避免调用线程阻塞的目的,从而提高软件的可响应性。甚至有些时候我们就认为多线程和异步操作是等同的概念。但是,多线程和异步操作还是有一些区别的。而这些区别造成了使用多线程和异步操作的时机的区别。  异步操作的本质   所有的程序最终都会由计算机硬件来执行,所以为了更好的理解异步操作的本质,我们有必要了解一下它的硬件基础。 熟悉电脑硬件的朋友肯定对DMA这个词不陌生,硬盘、光驱的技术规格中都有明确DMA的模式指标,其实网卡、声卡、显卡也是有DMA功能的。DMA就是直 接内存访问的意思,也就是说,拥有DMA功能的硬件在和内存进行数据交换的时候可以不消耗CPU资源。只要CPU在发起数据传输时发送一个指令,硬件就开 始自己和内存交换数据,在传输完成之后硬件会触发一个中断来通知操作完成。这些无须消耗CPU时间的I/O操作正是异步操作的硬件基础。所以即使在DOS 这样的单进程(而且无线程概念)系统中也同样可以发起异步的DMA操作。  线程的本质  线程不是一个计算机硬件的功能,而是操作系统提供的一种逻辑功能,线程本质上是进程中一段并发运行的代码,所以线程需要操作系统投入CPU资源来运行和调度。  异步操作的优缺点   因为异步操作无须额外的线程负担,并且使用回调的方式进行处理,在设计良好的情况下,处理函数可以不必使用共享变量(即使无法完全不用,最起码可以减少 共享变量的数量),减少了死锁的可能。当然异步操作也并非完美无暇。编写异步操作的复杂程度较高,程序主要使用回调方式进行处理,与普通人的思维方式有些 初入,而且难以调试。  多线程的优缺点  多线程的优点很明显,线程中的处理程序依然是顺序执行,符合普通人的思维习惯,所以编程简单。但是多线程的缺点也同样明显,线程的使用(滥用)会给系统带来上下文切换的额外负担。并且线程间的共享变量可能造成死锁的出现。  适用范围   在了解了线程与异步操作各自的优缺点之后,我们可以来探讨一下线程和异步的合理用途。我认为:当需要执行I/O操作时,使用异步操作比使用线程+同步 I/O操作更合适。I/O操作不仅包括了直接的文件、网络的读写,还包括数据库操作、Web Service、HttpRequest以及.net Remoting等跨进程的调用。  而线程的适用范围则是那种需要长时间CPU运算的场合,例如耗时较长的图形处理和算法执行。但是往 往由于使用线程编程的简单和符合习惯,所以很多朋友往往会使用线程来执行耗时较长的I/O操作。这样在只有少数几个并发操作的时候还无伤大雅,如果需要处 理大量的并发操作时就不合适了。  实例研究  说了那么理论上的东西,可能有些兄弟早就不耐烦了,现在我们来研究几个实际的异步操作例子吧。  实例1:由delegate产生的异步方法到底是怎么回事?  大家可能都知道,使用delegate可以“自动”使一个方法可以进行异步的调用。从直觉上来说,我觉得是由编译器或者CLR使用了另外的线程来执行目标方法。到底是不是这样呢?让我们来用一段代码证明一下吧。

    01using System; 02using System.Threading; 03  04namespace AsyncDelegateDemo 05{ 06  delegate void AsyncFoo(int i); 07  class Program 08  { 09    /// <summary> 10    /// 输出当前线程的信息 11    /// </summary> 12   /// <param name="name">方法名称</param> 13  14    static void PrintCurrThreadInfo(string name) 15    { 16      Console.WriteLine("Thread Id of " + name+ " is: " + Thread.CurrentThread.ManagedThreadId+ ", current thread is " 17      + (Thread.CurrentThread.IsThreadPoolThread ? "" : "not ") 18      + "thread pool thread."); 19    } 20  21    /// <summary> 22    /// 测试方法,Sleep一定时间 23    /// </summary> 24    /// <param name="i">Sleep的时间</param> 25    static void Foo(int i) 26    { 27       PrintCurrThreadInfo("Foo()"); 28       Thread.Sleep(i); 29    } 30  31    /// <summary> 32    /// 投递一个异步调用 33    /// </summary> 34    static void PostAsync() 35    { 36      AsyncFoo caller = new AsyncFoo(Foo); 37      caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller); 38    } 39  40    static void Main(string[] args) 41    { 42      PrintCurrThreadInfo("Main()"); 43      for(int i = 0; i < 10 ; i++) 44      { 45         PostAsync(); 46      } 47      Console.ReadLine(); 48    } 49  50    static void FooCallBack(IAsyncResult ar) 51    { 52      PrintCurrThreadInfo("FooCallBack()"); 53      AsyncFoo caller = (AsyncFoo) ar.AsyncState; 54      caller.EndInvoke(ar); 55    } 56  } 57}

     

     

    这段代码代码的输出如下:

    显示代码 打印 01Thread Id of Main() is: 1, current thread is not thread pool thread. 02  03Thread Id of Foo() is: 3, current thread is thread pool thread. 04  05Thread Id of FooCallBack() is: 3, current thread is thread pool thread. 06  07Thread Id of Foo() is: 3, current thread is thread pool thread. 08  09Thread Id of Foo() is: 4, current thread is thread pool thread. 10  11Thread Id of Foo() is: 5, current thread is thread pool thread. 12  13Thread Id of FooCallBack() is: 3, current thread is thread pool thread. 14  15Thread Id of Foo() is: 3, current thread is thread pool thread. 16  17Thread Id of FooCallBack() is: 4, current thread is thread pool thread. 18  19Thread Id of Foo() is: 4, current thread is thread pool thread. 20  21Thread Id of Foo() is: 6, current thread is thread pool thread. 22  23Thread Id of FooCallBack() is: 5, current thread is thread pool thread. 24  25Thread Id of Foo() is: 5, current thread is thread pool thread. 26  27Thread Id of Foo() is: 7, current thread is thread pool thread. 28  29Thread Id of FooCallBack() is: 3, current thread is thread pool thread. 30  31Thread Id of Foo() is: 3, current thread is thread pool thread. 32  33Thread Id of FooCallBack() is: 4, current thread is thread pool thread. 34  35Thread Id of FooCallBack() is: 6, current thread is thread pool thread. 36  37Thread Id of FooCallBack() is: 5, current thread is thread pool thread. 38  39Thread Id of FooCallBack() is: 7, current thread is thread pool thread. 40  41Thread Id of FooCallBack() is: 3, current thread is thread pool thread.

     

     

    从输出可以看出,.net使用delegate来“自动”生成的异步调用是使用了另外的线程(而且是线程池线程)。


    最新回复(0)