class DoWorks
{
//定一個一個委託
public delegate void CopyFileHandler(long lngPosition, long LngCount);
//定義一個事件(很重要),這個事件將被主線程捕捉,並對主線程的內容進行更改,比如:進度條。
public event CopyFileHandler CopyFileEvent;
//定義兩個字符串變量,sFile表示源文件,tFile表示目標文件,當然,這個可以使用屬性的方式,這個爲了簡單明瞭,直接使用共有變量。
public System.String sFile;
public System.String tFile;
//這個就是工作線程使用到的方法了。
public void CopyFile()
{
//定義一個字節數組,用來緩存從源文件讀到的字節流。
byte[] fb = new byte[2048];
//定義當前已讀字節數,用於主線程更新界面。
long lngPosition = 0;
//源文件流
FileStream sfs = new FileStream(sFile,System.IO.FileMode.Open,System.IO.FileAccess.Read);
//二進制文件讀取器
BinaryReader br = new BinaryReader(sfs);
br.BaseStream.Seek(0,System.IO.SeekOrigin.Begin);
if(File.Exists(tFile))
File.Delete(tFile);
//目標文件流
FileStream tfs = new FileStream(tFile,System.IO.FileMode.CreateNew,System.IO.FileAccess.Write);
//二進制文件寫入器
BinaryWriter bw = new BinaryWriter(tfs);
//源文件的大小
long positionLength = sfs.Length;
int k = 10000;
//當讀到的字節數小於2048,表示已經讀到文件流的末尾了。停止讀取
while(k>=2048)
{
k = br.Read(fb,0,fb.Length);
bw.Write(fb);
lngPosition += k;
//觸發事件(關鍵),參數:1、表示當前共讀取了多少,2、表示文件的長度
CopyFileEvent(lngPosition,positionLength);
}
tfs.Flush();
bw.Close();
br.Close();
tfs.Close();
sfs.Close();
}
}
這個大家看看應該沒有什麼吧。下面我們就使用這個類來進行文件的拷貝
2、按鈕的點擊事件處理方法:
private void button1_Click(object sender, System.EventArgs e)
{
DoWorks dw = new DoWorks();
//這兩個公有變量一定要賦值,因爲這次主要演示目的,一些判斷及異常處理省略了。
dw.sFile = sourceFile;
dw.tFile = targetFile;
//這個是關鍵,定義事件的處理方法。
dw.CopyFileEvent += new AsyncCopyFile.Form1.DoWorks.CopyFileHandler(this.ChgProgress);
//定義新線程。
Thread t = new Thread(new ThreadStart(dw.CopyFile));
//啓動線程
t.Start();
}
這裏用到一個this.ChgProgress方法,這個方法就是用來處理界面的顯示。
3、看一下事件處理方法:
private void ChgProgress(long k,long count)
{
this.progressBar1.Maximum = (int)count;
this.progressBar1.Minimum = 0;
this.progressBar1.Value = (int)k;
this.label4.Text = count.ToString();
this.label2.Text = k.ToString();
}