孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

分类: C# 484人阅读 评论(1) 收藏 举报

先举个例子:

有两个函数:

 

[csharp] view plaincopy
  1. //函数一:根据URL获取下载文件,读取其中的一部分并存到一个缓冲区数组中  
  2.  public byte[] readFile(string downLoadURL, int begin, int end)  
  3. {  
  4. }  
  5. //函数二:将缓冲区的数据写进文件中,并制定写入的位置  
  6. public void writeFile(byte[] buffer, int begin, FileStream fs)  
  7. {  
  8. lock(locker)  
  9. {...}  
  10. }  

 

 

过程是执行第一个函数获取缓冲区数据,然后执行第二个函数将上面获得的缓冲区数组写到filestream中。

启动三个线程,三个线程都执行这三个函数,怎么处理呢?

答案是:匿名函数

 

[csharp] view plaincopy
  1. Thread[] thread=new Thread[3];  
  2. for (int i = 0; i < 3; i++)  
  3. {  
  4.     thread[i] = new Thread(delegate()  
  5.     {  
  6.         byte[] buffer = readFile.readFile(textURL.Text, begin[i], end[i]);  
  7.         writeFile.writeFile(buffer,begin[i], fs);  
  8.     });  
  9.     thread[i].Start();  
  10. }  

匿名函数的写法:

 

 

[csharp] view plaincopy
  1. delegate()  
  2.     {  
  3.         byte[] buffer = readFile.readFile(textURL.Text, begin[i], end[i]);  
  4.         writeFile.writeFile(buffer,begin[i], fs);  
  5.     }  
posted on 2012-11-28 09:51  孤独的猫  阅读(681)  评论(0)    收藏  举报