程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#應用Parallel類停止多線程編程實例

C#應用Parallel類停止多線程編程實例

編輯:C#入門知識

C#應用Parallel類停止多線程編程實例。本站提示廣大學習愛好者:(C#應用Parallel類停止多線程編程實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用Parallel類停止多線程編程實例正文


終端完成年夜文件上傳一向都是比擬難的技巧,個中觸及到後端與前真個交互,穩固性和流量年夜小,並且完成道理每一個人都有本身的設法主意,後端主流用的比擬多的是Http來完成,由於年夜多完成過斷點下載。但穩固性不克不及包管,一旦斷開,沒法續傳。所以得采取另外一種風行的做法,TCP上傳年夜文件。 

網上查找了一些材料,年夜多半是斷點下載,然後就是零丁的C#真個上傳吸收,或是HTTP的,或是只要android真個,因為義務緊所以之前找的首選計劃固然是Http先來完成文件上傳,終端采取Post辦法,將文件直接傳至後端,後端經由過程File來取得。 

android端: 

RequestParams params = new RequestParams();
 File file = getTempFile();//取得當地文件
  try {
   params.put("file", file);
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  }
  AsyncHttpUtil.post(URL + "/UpLoad", params, new JsonHttpResponseHandler() {
……

後端:
 var file = Request.Files["file"];
  file.SaveAs(upFileName);
還有其它更好的處置辦法,也能夠傳流出去,欠亨過file文件格局。 在收集好的情形下沒甚麼成績,但收集差點後來常常上傳一半失落線或多個客戶端上傳湧現連不上的情形,關於年夜文件極不穩固,所以趕忙研發TCP協定文件斷點上傳。

也有網友完成了Http斷點上傳,既然年夜文件不可,那就將文件朋分成小文件來上傳,純NET的重要辦法: 

上傳: 

 bool result = true;
   long cruuent = 0;

   FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
   BinaryReader bReader = new BinaryReader(fStream); 
   
   //模仿斷點上傳,第一次只上傳 100 個字節
   long length = 100;

   fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);

   #region 開端上傳文件
   try
   {

    
    byte[] data; 
    #region 朋分文件上傳
    for (; cruuent <= length; cruuent = cruuent + byteCount)
    {
     if (cruuent + byteCount > length)
     {
      data = new byte[Convert.ToInt64((length - cruuent))];
      bReader.Read(data, 0, Convert.ToInt32((length - cruuent)));
     }
     else
     {
      data = new byte[byteCount];
      bReader.Read(data, 0, byteCount);
     }
     try
     {
      Hashtable parms = new Hashtable();
      parms.Add("fileName", fileName);
      parms.Add("npos", cruuent.ToString());

      byte[] byRemoteInfo = PostData(serverPath + "UpLoadServer.aspx", data, parms);

     }
     catch (Exception ex)
     {
      msg = ex.ToString();
      result = false;
      break;
     }
    #endregion
    }
   }
   catch (Exception ex)
   {
    msg = ex.ToString();
    result = false;
   }
   finally
   {
    bReader.Close();
    fStream.Close();

   }

   GC.Collect();

先將文件朋分成小流,npos為斷點的地位,即曾經上傳了的年夜小,然後輪回上傳一切包。
後台吸收: 

 /// <summary>
 /// 保留文件(從URL參數中獲得文件名、以後指針,將文件流保留到以後指針後)
 /// 假如是第一次上傳,則以後指針為0,代碼履行與續傳一樣,只不外指針沒有偏移
 /// </summary>
 public void SaveUpLoadFile()
 {

  string fileName = Request.Params["fileName"];
  long npos = Convert.ToInt64(Request.Params["npos"]);

  int upLoadLength = Convert.ToInt32(Request.InputStream.Length);
  
  string path = Server.MapPath("/UpLoadServer");
  fileName = path + "//UpLoad//" + fileName;

  FileStream fStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  //偏移指針
  fStream.Seek(npos, SeekOrigin.Begin);

  //從客戶真個要求中獲得文件流
  BinaryReader bReader = new BinaryReader(Request.InputStream);
  try
  {
   byte[] data = new byte[upLoadLength];
   bReader.Read(data, 0, upLoadLength);
   fStream.Write(data, 0, upLoadLength);
  }
  catch
  {
   //TODO 添加異常處置
  }
  finally
  {
   //釋放流
   fStream.Close();
   bReader.Close();
  }
 }

重點在 fStream.Seek(npos, SeekOrigin.Begin); 從斷點地位吸收保留。

有興致的可以本身完成。  

如今重要講講客戶端TCP上傳,後台TCP吸收,重要思緒為:android端讀取當地文件將文件名,文件年夜小上傳至辦事器(文件名必需是全局獨一),辦事器將依據文件名查詢能否上傳過,若是上傳過,將已傳文件的年夜小即斷點地位傳給終端,終端吸收後先保留斷點地位,然後從斷點地位讀取文件斷續上傳,直到全體完成。若沒上傳過則辦事器創立緩存文件吸收。 

看看代碼Android: 

String head = "Length=" + uploadFile.length() + ";filename=" + filename

 Socket socket = new Socket("192.168.0.123", 7080);
     OutputStream outStream = socket.getOutputStream();
     outStream.write(head.getBytes());//發送

     PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
     String response = StreamTool.readLine(inStream);//讀取
     String[] items = response.split(";");

 final String position = items[0].substring(items[0].indexOf("=") + 1);//斷點地位
      final String serviceurl = items[1].substring(items[1].indexOf("=") + 1);//保留到辦事器途徑

RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
      fileOutStream.seek(Integer.valueOf(position));//從斷點地位開端讀取文件
      byte[] buffer = new byte[1024];
      int len = -1;
      int length = Integer.valueOf(position);//曾經上傳的年夜小,用於當地顯示
      while ( (len = fileOutStream.read(buffer)) != -1) {
       outStream.write(buffer, 0, len);
       length += len;
       Message msg = new Message();
       msg.getData().putInt("size", length);
       // 更新上傳的進度       handler.sendMessage(msg);

      } if (length == uploadFile.length()) {//假如相等,則解釋上傳勝利} fileOutStream.close(); outStream.close(); inStream.close(); socket.close(); 

後端處置: 

 private static TcpListener listener;//辦事器監聽
 IPAddress ipHost = IPAddress.Any;
 listener = new TcpListener(ipHost, 7080);
     listener.Start();//開啟監聽

 Socket remoteSocketClient = listener.AcceptSocket();
     device = new Device(remoteSocketClient);
//開啟一個線程行止理
     threaddev = new Thread(new ThreadStart(device.Scan));
     device.curentThread = threaddev;
     threaddev.IsBackground = true;
     threaddev.Start();

Scan處置辦法:

string[] items = strGetContent.Split(';');
     string filelength = items[0].Substring(items[0].IndexOf("=") + 1);
     string filename = items[1].Substring(items[1].IndexOf("=") + 1);
 //文件保留完全途徑
       filePath = Path.Combine(directoryPath, filename);
//斷點地位
      long position = 0;
      if (File.Exists(filePath))
      {
       using (FileStream reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
       {
        position = reader.Length;
       }
      }
//前往新聞
 response = "position=" + position + ";serviceurl=" + dirPath + "/" + filename) ;
      

      //辦事器收到客戶真個要求信息後,給客戶端前往呼應信息:;position=0 
      //serviceurl 辦事生保留的文件地位 /PlayFiles/video/2016/07/04/1141142221.mp4
      bufferSend = Encoding.UTF8.GetBytes(response);
      remoteSocketClient.Send(bufferSend);

然後處置續傳內容:

//取得文件內容
      byte[] buffer = new byte[BufferSize];
      int received = 0;
      long receive, length = long.Parse(filelength);
      FileInfo file = new FileInfo(filePath);
      using (FileStream writer = file.Open(file.Exists ? FileMode.Append : FileMode.CreateNew, FileAccess.Write, FileShare.None))
      {
       receive = writer.Length;
       while (receive < length)
       {
        if ((received = remoteSocketClient.Receive(buffer)) == 0)
        {
         Program.MessageAdd(" IP【" + remoteSocketClient.RemoteEndPoint.ToString() + "】吸收暫停!");
         break;
        }
        writer.Write(buffer, 0, received);
        writer.Flush();
        receive += (long)received;
       }

      }

if (receive == length)
      {
       Program.MessageAdd(" IP【" + remoteSocketClient.RemoteEndPoint.ToString() + "】吸收" + filename + "完成!");
}

重要道理照樣從斷點地位上傳和吸收。 

這裡只是講了最重要的代碼功效,還有許多細節處置,好比終端要顯示進度,所以還要保留進度,後端文件的保留會不會錯位,還有多文件上傳會不會亂,多客戶端上傳是創立新線程照樣有線程池來處置等等 。

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved