简体   繁体   English

Windows应用商店应用,使用线程下载多个文件

[英]Windows Store Apps, download multiple files with threads

I have this following method that I use to download a file's content: 我有以下方法用于下载文件的内容:

public async Task<String> DownloadFileService(String filePath, string id)
{
    string resposta = string.Empty;
    try
    {
        using (var httpClient = new HttpClient { BaseAddress = Constants.baseAddress })
        {
            string token = App.Current.Resources["token"] as string;
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            string fname = Path.GetFileName(filePath);
            string path = Path.GetDirectoryName(filePath);
            path = path.Replace(fname, "");
            StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(Constants.DataDirectory + "\\" + path, CreationCollisionOption.OpenIfExists);

            StorageFile imgFile = await folder.CreateFileAsync(fname, CreationCollisionOption.ReplaceExisting);

            using (var response2 = await httpClient.GetAsync("file?fileId=" + id))
            {

                Stream imageStream = await response2.Content.ReadAsStreamAsync();
                byte[] bytes = new byte[imageStream.Length];

                imageStream.Read(bytes, 0, (int)imageStream.Length);


                await FileIO.WriteBytesAsync(imgFile, bytes);
                resposta = Convert.ToBase64String(bytes);
            }

        }
        return resposta;
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}

I would like to know how I can call this multiple times to download several files at same time and wait until all files are downloaded, then do other stuff. 我想知道如何多次调用它来同时下载几个文件并等待所有文件下载,然后做其他的事情。

EDIT 编辑

After this suggestion I tried creating the following method: 建议之后,我尝试创建以下方法:

public async void checkFilesExist(JsonArray array, string path)
{
    List<Document> list = new List<Document>();
    ObjectsService obj = new ObjectsService();
    List<Task> ts = new List<Task>();

    foreach (var item in array)
    {
        JsonObject newDoc;
        JsonObject.TryParse(item.Stringify(), out newDoc);

        if (newDoc.ContainsKey("libraryType") || !newDoc.ContainsKey("fileName"))
            continue;
        string name = newDoc["fileName"].GetString();
        string id = newDoc["_id"].GetString();
        File file = new File(name);
        file.id = id;
        Document doc = file;
        doc.Parent = Document.FromPath(path);

        path = path.Replace("/", "\\");
        StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(Constants.DataDirectory + "\\" + path, CreationCollisionOption.OpenIfExists);
        try
        {
            await folder.GetFileAsync(file.Name);
        }
        catch (Exception e)
        {
            list.Add(doc);
            Task x = obj.DownloadFileService(doc.GetFullPath(), file.id);
            ts.Add(x);
            Debug.WriteLine(" Ex: " + e.Message);
        }
    }
    try
    {
        Task.WaitAll(ts.ToArray());
        Debug.WriteLine("AFTER THrEADS");
    }
    catch (Exception e)
    {
        Debug.WriteLine("Ex2:  " + e.Message);
    }
}

What this does is, with a response in json I get from a webservice listing some files, I check if they already exist in localfolder. 这是做什么的,通过json中的响应我从列出一些文件的web服务中获取,我检查它们是否已经存在于localfolder中。 If they don't I call the method I had at start of the question. 如果他们不这样做,我会打电话给我在问题开头的方法。

I then have a list of tasks, and I add the call of the DownloadFileService() as a new task in the list, after that I do the Task.WaitAll() to wait for the downloads to finish. 然后我有一个任务列表,我将DownloadFileService()的调用添加为列表中的新任务,之后我执行Task.WaitAll()以等待下载完成。

Using fiddler I see the downloads all start, but for some reason my code doesn't stop at Task.WaitAll() , it just keeps going and it starts to use the files that are still being downloaded, creating a bunch of problems :D 使用fiddler我看到下载全部开始,但由于某种原因,我的代码没有停在Task.WaitAll() ,它只是继续前进,它开始使用仍在下载的文件,产生一堆问题:D

you can use Task.WaitAll . 你可以使用Task.WaitAll It waits for all of the provided Task objects to complete execution. 它等待所有提供的Task对象完成执行。

var t1 = DownloadFileService("file1", "1");
var t2 = DownloadFileService("file2", "2");
var t3 = DownloadFileService("file3", "3");

Tasks.WaitAll(t1, t2, t3);

Or you can use : 或者您可以使用:

await  DownloadFileService("Path", "id");
await  DownloadFileService("Path", "id");
await  DownloadFileService("Path", "id");
await  DownloadFileService("Path", "id");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM