C# 多线程与异步操作实现的探讨(推荐)

        随着拥有多个硬线程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使用了另外的线程来执行目标方法。到底是不是这样呢?让我们来用一段代码证明一下吧。

01 using System;
02 using System.Threading;
03  
04 namespace 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 }

 

 

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

01 Thread Id of Main() is: 1, current thread is not thread pool thread.
02  
03 Thread Id of Foo() is: 3, current thread is thread pool thread.
04  
05 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
06  
07 Thread Id of Foo() is: 3, current thread is thread pool thread.
08  
09 Thread Id of Foo() is: 4, current thread is thread pool thread.
10  
11 Thread Id of Foo() is: 5, current thread is thread pool thread.
12  
13 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
14  
15 Thread Id of Foo() is: 3, current thread is thread pool thread.
16  
17 Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
18  
19 Thread Id of Foo() is: 4, current thread is thread pool thread.
20  
21 Thread Id of Foo() is: 6, current thread is thread pool thread.
22  
23 Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
24  
25 Thread Id of Foo() is: 5, current thread is thread pool thread.
26  
27 Thread Id of Foo() is: 7, current thread is thread pool thread.
28  
29 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
30  
31 Thread Id of Foo() is: 3, current thread is thread pool thread.
32  
33 Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
34  
35 Thread Id of FooCallBack() is: 6, current thread is thread pool thread.
36  
37 Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
38  
39 Thread Id of FooCallBack() is: 7, current thread is thread pool thread.
40  
41 Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
原文地址:https://www.cnblogs.com/hummersofdie/p/2221047.html