Windows应用商店应用,使用主题

时间:2015-06-10 10:28:11

标签: c# .net multithreading windows-store-apps httpclient

我使用以下方法下载文件的内容:

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);
    }
}

我想知道如何多次调用它来同时下载多个文件并等到所有文件都下载完毕,然后再做其他事情。

修改

this建议后,我尝试创建以下方法:

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);
    }
}

这是做什么的,通过json中的响应我从列出一些文件的web服务中获取,我检查它们是否已经存在于localfolder中。 如果他们不这样做,我会打电话给我在问题开始时使用的方法。

然后我有一个任务列表,我将DownloadFileService()的调用添加为列表中的新任务,之后我执行Task.WaitAll()等待下载完成。< / p>

使用fiddler我看到下载全部开始,但由于某些原因我的代码不会停在Task.WaitAll(),它只是继续前进并开始使用仍在下载的文件,创建一堆问题:D

2 个答案:

答案 0 :(得分:4)

您可以使用Task.WaitAll。它等待所有提供的Task对象完成执行。

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

Tasks.WaitAll(t1, t2, t3);

答案 1 :(得分:1)

或者您可以使用:

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