异步和多线程的应用场景总结

结论:

计算密集型工作,采用多线程。

IO密集型工作,采用异步机制。

原因:

要理解这一点,需要从“IO操作的DMA(Direct Memory Access)模式”开始讲起。DMA即直接内存访问,是一种不经过CPU而直接进行内存数据存储的数据交换模式。通过DMA的数据交换几乎可以不损耗CPU的资源。在硬件中,硬盘、网卡、声卡、显卡等都有DMA功能。CLR所提供的异步编程模型就是让我们充分利用硬件的DMA功能来释放CPU的压力。

举例:

1)多线程 

private void buttonGetPagebyThread_Click(object sender, EventArgs e)
{
  Thread t = new Thread(() =>
  {
    var request = HttpWebRequest.Create("http://www.cnblogs.com/my-opinion");
    var response = request.GetResponse();
    var stream = response.GetResponseStream();
    using (StreamReader reader = new StreamReader(stream))
    {
      operateGUI(reader);
    }
  });

  t.Start();
}

private void operateGUI(StreamReader reader)
{
  StringBuilder content = new StringBuilder();
  while (reader.Peek() >= 0)
  {
    content.Append(reader.ReadLine());
  }

  Action<string> action = delegate(string s)
  {
    rb_Content.AppendText(s);
  };

  if (rb_Content.InvokeRequired)
  {
    rb_Content.Invoke(action, content.ToString());
  }
  else
  {
    rb_Content.AppendText(content.ToString());
  }

2)异步

private void buttonGetPage_Click(object sender, EventArgs e)
{
  var request = HttpWebRequest.Create("http://www.sina.com.cn");
  request.BeginGetResponse(this.AsyncCallbackImpl, request);
}

public void AsyncCallbackImpl(IAsyncResult ar)
{
  WebRequest request = ar.AsyncState as WebRequest;
  var response = request.EndGetResponse(ar);
  var stream = response.GetResponseStream();
  using (StreamReader reader = new StreamReader(stream))
  {
    operateGUI(reader);
  }
}

private void operateGUI(StreamReader reader)
{
  StringBuilder content = new StringBuilder();
  while (reader.Peek() >= 0)
  {
    content.Append(reader.ReadLine());
  }

  Action<string> action = delegate(string s)
  {
    rb_Content.AppendText(s);
  };

  if (rb_Content.InvokeRequired)
  {
    rb_Content.Invoke(action, content.ToString());
  }
  else
  {
    rb_Content.AppendText(content.ToString());
  }

异步和多线程的应用场景总结,布布扣,bubuko.com

异步和多线程的应用场景总结

上一篇:《Java性能优化权威指南》


下一篇:LuajavaBridge 声音捕捉