C#多线程与异步的区别详解

2019-12-30 17:43:21于丽

而线程的适用范围则是那种需要长时间 CPU 运算的场合,例如耗时较长的图形处理和算法执行。但是往往由于使用线程编程的简单和符合习惯,所以很多朋友往往会使用线程来执行耗时较长的 I/O 操作。这样在只有少数几个并发操作的时候还无伤大雅,如果需要处理大量的并发操作时就不合适了。

实例研究

说了那么理论上的东西,可能有些兄弟早就不耐烦了,现在我们来研究几个实际的异步操作例子吧。

实例1:由 delegate 产生的异步方法到底是怎么回事?

大家可能都知道,使用 delegate 可以“自动”使一个方法可以进行异步的调用。从直觉上来说,我觉得是由编译器或者 CLR 使用了另外的线程来执行目标方法。到底是不是这样呢?让我们来用一段代码证明一下吧。


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.