2011年11月14日 星期一

Stop WebClinet.DownloadFiles() in MultiThread

使用WebClinet在multithread環境下下載檔案時的停止方式

ThreadList為 List元件 Thread形態的全域變數

假定Thread宣告內容為
Thread t1 = new Thread(() =>;
{
 try
 {
  using (WebClient mywebclient = new WebClient())
  {
   string sUrlToReadFileFrom = ImageUrl;
   string sFilePathToWriteFileTo = targeturl;
   Stream streamRemote = null;
   Stream streamLocal = null;
   using (WebClient client = new WebClient())
   {
    try
    {
     streamRemote = client.OpenRead(sUrlToReadFileFrom);

     streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None);

     int iByteSize = 0;
     byte[] byteBuffer = new byte[4096];

     while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
     {
      streamLocal.Write(byteBuffer, 0, iByteSize);
     }
    }
    catch (System.Net.WebException){// 可加入console.write}
    catch (Exception){// 可加入console.write}

    if (streamLocal != null){
streamLocal.Close();}
    if (streamRemote != null){streamRemote.Close();}
   }
  }
 }
 catch (System.Net.WebException){// 可加入console.write}
 catch (Exception){// 可加入console.write}
 ThreadList.Add(t1); 

 t1.Start();
}

停止則是另開了一個BackgroundWorker來進行
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
 int icount = 0;
 for (int ia = 0; ia < ThreadList.Count; ia++)
 {
  if (ThreadList[ia].IsAlive)
  {
   ThreadList[ia].Interrupt();
   icount++;
  }
  else
  {
   ThreadList[ia] = null;
  }
 }
 Thread.Sleep(500);
 bool totalStop = false;
 while (!totalStop)
 {
  totalStop = true;
  icount = 0;
  Thread.Sleep(500);
  for (int ia = 0; ia < ThreadList.Count; ia++)
  {
   if (ThreadList[ia] != null)
   {
    if (ThreadList[ia].IsAlive)
    {
     totalStop = false;
     icount++;
    }
    else
    {
     ThreadList[ia] = null;
    }
   }
  }
 }
}


by Keng-li.Lin

沒有留言:

張貼留言