我在下载局域网的压缩包的时候,背景在播放视频,在下载的过程中,还有写入数据的时候,播放的视频会卡住。我在想是不是把下载和写入以及后面的压缩的操作,开一个线程,在线程里面处理会不会更好一点,只是我用的UnityWebRequest来加载,需要写在协程里。我看网上有用HttpWebRequest来实现多线程加载,但是我觉得应该是我思路有问题。有人能帮我解惑么。
///
/// 批量下载压缩包并解压
///
/// <param name="downloadPath"> 下载文件夹路径 </param>
/// <param name="savePath">保存文件夹路径</param>
/// <param name="LoadProgress">加载进度的回调</param>
/// <param name="DownLoad">完成回调</param>
/// <returns></returns>
public IEnumerator DownLoadAllZipAssetByWeb(string downloadPath, string savePath, Action<UnityWebRequest,int,int> LoadProgress, Action DownLoad)
{
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
Debug.Log("进入下载的路径:" + downloadPath);
Debug.Log("进入安装的路径:" + savePath);
string directoryDownloadPath = ToDirectoryUrl(downloadPath);
Debug.Log("查询文件夹的路径:" + directoryDownloadPath);
//得到所有的文件件路径和所有文件的路径
getSourceFolder(directoryDownloadPath);
Debug.Log("文件的数量:" + fileVessel.Count);
int allFileCount = fileVessel.Count;
int currentDownloadCount = 0;
for (int i = 0; i < folderVessel.Count; i++)
{
string tp = folderVessel[i].Replace(directoryDownloadPath, savePath);
Directory.CreateDirectory(tp);
}
UnityWebRequest request = null;
for (int i = 0; i < fileVessel.Count; i++)
{
currentDownloadCount = i+1;
string newSaveUrl = fileVessel[i].Replace(directoryDownloadPath, savePath);
string newDownloadUrl = ToWebRequestUrl(fileVessel[i]);
packageVessel.Add(newSaveUrl);
Debug.Log("下载的路径:" + newDownloadUrl);
Debug.Log("安装的路径:" + newSaveUrl);
request = UnityWebRequest.Get(newDownloadUrl);
if (LoadProgress != null)
{
LoadProgress(request,currentDownloadCount, allFileCount);
}
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log("Download Error:" + request.error);
}
else if (request.isDone)
{
byte[] results = request.downloadHandler.data;
FileInfo fileInfo = new FileInfo(newSaveUrl);
FileStream fs = fileInfo.Create();
fs.Write(results, 0, results.Length);
fs.Flush(); //文件写入存储到硬盘
fs.Close(); //关闭文件流对象
fs.Dispose(); //销毁文件对象
}
}
request.Dispose();
for (int i = 0; i < packageVessel.Count; i++)
{
//开始解压
FileStream fileStream = new FileStream(packageVessel[i], FileMode.Open);
DecompressToDirectory(fileStream, savePath);
//UnzipWithChineseFilesOrDirs(packageVessel[i], savePath);
//FileInfo info = new FileInfo(packageVessel[i]);
//info.Delete();
}
if (DownLoad != null)
DownLoad();
}