c# - Windows Store Apps,使用线程下载多个文件

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

它的作用是,通过我从列出一些文件的 Web 服务获得的 json 响应,我检查它们是否已经存在于本地文件夹中。 如果他们不这样做,我会调用我在问题开始时使用的方法。

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

使用 fiddler 我看到所有下载都开始了,但出于某种原因我的代码并没有在 Task.WaitAll() 处停止,它一直在继续并开始使用仍然存在的文件正在下载,造成一堆问题 :D

最佳答案

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

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

Tasks.WaitAll(t1, t2, t3);

关于c# - Windows Store Apps,使用线程下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30753700/

相关文章:

c# - 部署到 Azure 后不显示单个图像

javascript - 设置打印纸尺寸的最小高度?

c# - C#中bigint的等价物是什么?

c# - 如何阻止应用程序使用我的 api key ?

c# - "C# compiler as a service "的状态是什么

c# - 对实例的序列化和反序列化使用react

java - thymeleaf | TemplateEngine.process 是线程安全操作吗?

java - 我得到一个 java.net.SocketException : Connection reset error

java - 如何从服务器下载文件

c# - 如何在 C# 中以编程方式查找项目文件夹