c# 多线程与异步调用

  异步操作的本质

  在方法调用前为异步方法指定一个回调函数,方法调用后被线程池中的一个线程接管,执行该方法。主线程立即返回,继续执行其他工作或响应用户请求。如果异步方法执行完    毕,回调函数被自动执行,以处理异步方法的调用结果。 如何实现异步方法呢?C#通过异步委托调用BeginInvoke和EndInvoke方法来实现异步方法。

  BeginInvoke方法原型: IAsyncResult BeginInvoke(......, AsyncCallback callback, object o); ......表示异步委托中定义的参数列表。 AsyncCallback参数是一个用于  回调函数的委托,它的原型为: public delegate void AsyncCallback(IAsyncResult ar)。其中IAsyncResult参数用于包装异步方法的执行结果。 Object参数用于在主线程与回调函数间传递一些附加信息,如同步信息。

EndInvoke方法原型: xxx EndInvoke(IAsyncResult result); xxx表示异步委托原型中定义的返回数据类型,IAsyncResult用于包装异步方法的执行结果。

  线程的本质
  线程不是一个计算机硬件的功能,而是操作系统提供的一种逻辑功能,线程本质上是进程中一段并发运行的代码,所以线程需要操作系统投入CPU资源来运行和调度。

  异步操作的优缺点

  因为异步操作无须额外的线程负担,并且使用回调的方式进行处理,在设计良好的情况下,处理函数可以不必使用共享变量(即使无法完全不用,最起码可以减少共享变量的数量),减少了死锁的可能。当然异步操作也并非完美无暇。编写异步操作的复杂程度较高,程序主要使用回调方式进行处理,与普通人的思维方式有些初入,而且难以调试。

  多线程的优缺点
  多线程的优点很明显,线程中的处理程序依然是顺序执行,符合普通人的思维习惯,所以编程简单。但是多线程的缺点也同样明显,线程的使用(滥用)会给系统带来上下文切换的额外负担。并且线程间的共享变量可能造成死锁的出现。

  适用范围

  在了解了线程与异步操作各自的优缺点之后,我们可以来探讨一下线程和异步的合理用途。我认为:当需要执行I/O操作时,使用异步操作比使用线程+同步I/O操作更合适。I/O操作不仅包括了直接的文件、网络的读写,还包括数据库操作、Web Service、HttpRequest以及.Net Remoting等跨进程的调用。
  而线程的适用范围则是那种需要长时间CPU运算的场合,例如耗时较长的图形处理和算法执行。但是往往由于使用线程编程的简单和符合习惯,所以很多朋友往往会使用线程来执行耗时较长的I/O操作。这样在只有少数几个并发操作的时候还无伤大雅,如果需要处理大量的并发操作时就不合适了。

下面看个异步调用的实例:

using System;
using System.Threading;

namespace AsyncDelegateDemo
{
  delegate void AsyncFoo(int i);
  class Program
  {
    ///<summary>
    /// 输出当前线程的信息
    ///</summary>
   ///<param name="name">方法名称</param>

    static void PrintCurrThreadInfo(string name)
    {
      Console.WriteLine("Thread Id of " + name+ " is: " + Thread.CurrentThread.ManagedThreadId+ ", current thread is "
      + (Thread.CurrentThread.IsThreadPoolThread ? "" : "not ")
      + "thread pool thread.");
    }

    ///<summary>
    /// 测试方法,Sleep一定时间
    ///</summary>
    ///<param name="i">Sleep的时间</param>
    static void Foo(int i)
    {
       PrintCurrThreadInfo("Foo()");
       Thread.Sleep(i);
    }

    ///<summary>
    /// 投递一个异步调用
    ///</summary>
    static void PostAsync()
    {
      AsyncFoo caller = new AsyncFoo(Foo);
      caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller);
    }

    static void Main(string[] args)
    {
      PrintCurrThreadInfo("Main()");
      for(int i = 0; i < 10 ; i++)
      {
         PostAsync();
      }
      Console.ReadLine();
    }

    static void FooCallBack(IAsyncResult ar)
    {
      PrintCurrThreadInfo("FooCallBack()");
      AsyncFoo caller = (AsyncFoo) ar.AsyncState;
      caller.EndInvoke(ar);

    }
  }
}  

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

Thread Id of Main() is: 1, current thread is not thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 4, current thread is thread pool thread.
Thread Id of Foo() is: 5, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
Thread Id of Foo() is: 4, current thread is thread pool thread.
Thread Id of Foo() is: 6, current thread is thread pool thread.
Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
Thread Id of Foo() is: 5, current thread is thread pool thread.
Thread Id of Foo() is: 7, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
Thread Id of FooCallBack() is: 6, current thread is thread pool thread.
Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
Thread Id of FooCallBack() is: 7, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.  
原文地址:https://www.cnblogs.com/colder/p/4486116.html