1

在按钮事件函数中,我有一个下载多个文件的多重链接。要下载这些文件,我有以下代码:

        for (int l = 0; l < itemLinks.Count(); l++)
        {
            string[] sourceParts = itemLinks[l].Split('/');
            string fileName = sourceParts[sourceParts.Count() - 1];
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.OpenReadCompleted += client_OpenReadCompleted;
            client.OpenReadAsync(new Uri(itemLinks[l]));
        }

在 OpenReadCompletedEventArgs 的以下函数中,我需要知道哪个文件的下载完成:

    async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        string pff = e.ToString();
        byte[] buffer = new byte[e.Result.Length];
        await e.Result.ReadAsync(buffer, 0, buffer.Length);

        using (IsolatedStorageFile storageFile =    
                   IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream stream = storageFile
                             .OpenFile(FILE_NAME, FileMode.Create))
            {
                await stream.WriteAsync(buffer, 0, buffer.Length);
            }
        }

        //Also I need to do some stuff here with FILE_NAME
      }

如何将 FILE_NAME 值发送到 client_OpenReadCompleted?

我不能将值保存在全局变量中,因为它会在 for 语句的每次调用中发生变化,我也尝试将变量发送为 += (sender, eventArgs) => 但是我的代码中有 await 这迫使我将按钮功能更改为异步

4

2 回答 2

2

OpenReadAsync有一个需要“userToken”参数的重载。它就是为此目的而设计的。

调用时OpenReadAsync,将此重载与您的变量一起使用:

client.OpenReadAsync(new Uri(itemLinks[l]), fileName);

然后,在事件处理程序中,检索它:

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    string fileName = (string)e.UserState;

    // ...
}
于 2013-09-15T11:58:12.497 回答
0

由于您正在使用await,因此如果您使用HttpClient而不是 ,则可以使用更清洁的解决方案WebClient

await Task.WhenAll(itemLinks.Select(DownloadAsync));

private static async Task DownloadAsync(string itemLink)
{
    string[] sourceParts = itemLinks[l].Split('/');
    string fileName = sourceParts[sourceParts.Count() - 1];
    using (var client = new HttpClient())
    using (var source = await client.GetStreamAsync(itemLink))
    using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
    using (IsolatedStorageFileStream stream = storageFile.OpenFile(FILE_NAME, FileMode.Create))
    {
        await source.CopyToAsync(stream);
    }

    ... // Use fileName
}

我不完全确定CopyToAsyncWP8 是否可用(它可能是 WP8 的一部分Microsoft.Bcl.Async)。如果不是,您可以删除该GetStreamAsync行并将该行替换为CopyToAsync

var buffer = await client.GetBytes(itemLink);
await stream.WriteAsync(buffer, 0, buffer.Length);
于 2013-09-15T15:23:25.387 回答