111,092
社区成员




public bool DoDownLoad(List<DownloadFile> downloadFiles)
{
try
{
//cpu核心数为线程数
int processorCount = Environment.ProcessorCount>=5? Environment.ProcessorCount:5;
ManualResetEvent[] startEvents = new ManualResetEvent[processorCount];
ManualResetEvent[] doneEvents = new ManualResetEvent[processorCount];
ThreadParam[] Params = new ThreadParam[processorCount];
Thread[] threads = new Thread[processorCount];
for (int i = 0; i < processorCount; ++i)
{
startEvents[i] = new ManualResetEvent(false);
doneEvents[i] = new ManualResetEvent(false);
Params[i] = new ThreadParam
{
MId = i, //线程ID
MStartEvent = startEvents[i], //启动下载事件
MDoneEvent = doneEvents[i] //完成下载事件
};
threads[i] = new Thread(new ParameterizedThreadStart(AsyncDownloadFile));
threads[i].Start(Params[i]);
}
//始终只有Environment.ProcessorCount多个线程在下载一个文件,你可以根据实际情况修改
for (int i = 0; i < downloadFiles.Count; ++i)
{
DownloadFile f = downloadFiles[i];
//分配线程下载任务
CutFile(Params, f.MFileSize);
for (int j = 0; j < processorCount; ++j)
{
Params[j].MUrl = f.MUrl;//文件下载地址
Params[j].MFileName = f.MFileName;//文件名称
Params[j].MDoneEvent.Reset(); //清空下载完成
Params[j].MStartEvent.Set(); //启动线程
}
//等待下载中...
WaitHandle.WaitAll(doneEvents);
//将临时文件合并为完整文件
MergeFile(Params);
}
return true;
}
catch (Exception err)
{
return false;
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
WpfApplication1.App app = new WpfApplication1.App();
app.InitializeComponent();
app.Run();
}