The business to be performed is to download nearly 40,000 pieces of audio from Alibaba Cloud to the local area, and a single download is very slow, so I want to use multi-threading, and allocate 20 threads to download at the same time, saving a lot of time class Program {
static void Main(string[] args) { string sql = "select en_audio,us_audio from t_audio LIMIT 198 "; MySqlDataReader mySqlDataReader = DBHelper.ExecuteReader(sql); List<String> sList = new List<String>(); sList.Add("https://qutifen-qudao.oss-cn-beijing.aliyuncs.com/mfg/audio/v3/1abacus_en.ogg"); sList.Add("https://qutifen-qudao.oss-cn-beijing.aliyuncs.com/mfg/audio/v3/2abacus_en.ogg"); if (mySqlDataReader.HasRows) { while (mySqlDataReader.Read()) { sList.Add(mySqlDataReader.GetString(0)); sList.Add(mySqlDataReader.GetString(1)); } } Console.WriteLine(sList.Count); Stopwatch stopwatch = new Stopwatch(); stopwatch. Start(); ThreadStart(sList); WaitHandle.WaitAll(waits); All threads in the listen wait have been set before executing the following code, otherwise they will be waiting here stopwatch. Stop(); Console.WriteLine($"Time-consuming{stopwatch. ElapsedMilliseconds}milliseconds"); Console.ReadKey();
} static Thread[] threads = new Thread[20]; static WaitHandle[] waits = new WaitHandle[20]; public static void ThreadStart(List<String> nums) { Assign threads for (int i=0; i<20; i++) { threads[i] = new Thread(DownLoadFile); waits[i] = new AutoResetEvent(false);
} Assign data to each thread to execute and start execution for (int i = 0; i < 20; i++) { if (i== threads. Length-1) { var retult = nums. Skip(nums. Count / 20 * i). Take(nums. Count- nums. Count / 20*i). ToList(); threads[i]. Start(new Objpt() { sList = retult, WaitHandle = waits[i], ThreadIndex = i }); } else { var retult= nums. Skip(nums. Count / 20 * i). Take(nums. Count / 20). ToList(); threads[i]. Start(new Objpt() { sList= retult, WaitHandle=waits[i], ThreadIndex=i }); }
} }
public static void DownLoadFile(Object obj) { int count = 0; Objpt optObj = (obj as Objpt); var sList = optObj.sList; Console.WriteLine($"Thread{optObj.ThreadIndex} started"; foreach (var url in sList) { try { count++; var arrs = url. Split('/'); WebRequest request = WebRequest.Create(url); HttpWebResponse res = (HttpWebResponse)request. GetResponse(); WebResponse response = request. GetResponse(); if (res. StatusCode.ToString() == "OK") { Stream responseStream = response. GetResponseStream(); using (FileStream fsWrite = new FileStream($"F:/Audio/v4/{arrs[arrs. Length - 2]}/{arrs[arrs. Length - 1]}", FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = new byte[response. ContentLength]; while (true) { Returns the number of bytes actually read this time int r = responseStream.Read(buffer, 0, buffer. Length); if (r == 0) { break; } fsWrite.Write(buffer, 0, r); write
} } } //if (count % 20 == 0 || count == sList.Count) //{ Console.WriteLine($"Thread{optObj.ThreadIndex} processed:{count}"); //}
} catch (Exception ex) { string strErrorLogFile = System.AppDomain.CurrentDomain.BaseDirectory + $"\\{optObj.ThreadIndex}ErrorLog.log"; if (! System.IO.File.Exists(strErrorLogFile)) System.IO.File.WriteAllText(strErrorLogFile, "//System ErrorLog File\r\n"); object objSql = "thread" + optObj.ThreadIndex.ToString() + ex. Message; System.IO.File.AppendAllText(strErrorLogFile, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + objSql.ToString() + url + "\r\n");
}
} Console.WriteLine($"Thread{optObj.ThreadIndex} ends"); (optObj.WaitHandle as AutoResetEvent). Set(); set method is to mark when a thread ends } }
public class Objpt { public List<String> sList { get; set; } public WaitHandle WaitHandle { get; set; } public int ThreadIndex { get; set; }
}
|