在Windows Phone 8的下载图片(Download Image in Windows Ph

2019-10-29 13:53发布

我必须下载和保存大量的图像,以本地文件夹。 我也有,而图像下载到更新UI。 现在,我使用下面的代码通过一个下载图像之一。 但问题是UI被阻塞每个下载请求。 我应该如何处理下载方法? 我不知道很多有关线程。 谁能帮我配好方法?

public async Task<T> ServiceRequest<T>(string serviceurl, object request)
{
    string response = "";
    httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest;
    httpwebrequest.Method = "POST";

    httpwebrequest.ContentType = "application/json";
    byte[] data = Serialization.SerializeData(request);

    using (var requestStream = await Task<Stream>.Factory.FromAsync(httpwebrequest.BeginGetRequestStream, httpwebrequest.EndGetRequestStream, null))
    {
        await requestStream.WriteAsync(data, 0, data.Length);
    }

    response = await httpRequest(httpwebrequest);

    var result = Serialization.Deserialize<T>(response);
    return result;
}


public async Task<string> httpRequest(HttpWebRequest request)
{
    try
    {
        string received;

        using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
        {
            using (var responseStream = response.GetResponseStream())
            {
                using (var sr = new StreamReader(responseStream))
                {
                    received = await sr.ReadToEndAsync();
                }
            }            
            response.Close();
        }

        return received;
    }
    catch(Exception ex)
    {
        return "";
    }
}

Answer 1:

我会建议你使用System.Net.Http.HttpClient 。 你可以从你的的NuGet得到它,只需选择搜索选项,包括预发行渠道为好。 有一个陷阱,但:它不是官方尚未公布,所以你不能在生产代码,现在用它。 还有的时候会终于发布上没有字。 但如果你只是学习,你可以自由地使用它。 它使事情像你描述的非常简单。 下面是我的代码,可巧:),你想要做这,正是一个示例:

private IEnumerable<string> CountPictures(int from, int to, string folder)
{
    for (int i = from; i < to; i++)
        yield return string.Format("{0}/image{1}.jpg", folder, i.ToString("D2"));
}

private async Task ImportImages()
{
    HttpClient c = new HttpClient();
    int count = 0;
    c.BaseAddress = new Uri("http://www.cs.washington.edu/research/imagedatabase/groundtruth/", UriKind.Absolute);
    foreach (var pic in CountPictures(1, 48, "leaflesstrees"))
    {
        var pic_response = await c.GetAsync(pic, HttpCompletionOption.ResponseContentRead);
        if (pic_response.IsSuccessStatusCode)
        {
            await SaveImageAsync(pic.Replace('/', '_'), await pic_response.Content.ReadAsStreamAsync());
            Debug.WriteLine(pic + " imported");
            count++;
        }
    }           
    Debug.WriteLine(string.Format("{0} images imported", count));
}

private Task SaveImageAsync(string filename, Stream stream)
{
    var task = Task.Factory.StartNew(() =>
    {
        if (stream == null || filename == null)
        {
            throw new ArgumentException("one of parameters is null");
        }
        try
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream targetStream = isoStore.OpenFile(filename, FileMode.Create, FileAccess.Write))
                {
                    byte[] readBuffer = new byte[4096];
                    int bytesRead = -1;
                    stream.Position = 0;
                    targetStream.Position = 0;

                    while ((bytesRead = stream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                    {
                        targetStream.Write(readBuffer, 0, bytesRead);
                    }
                }
            }
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine("DocumentStorageService::LoadImage FAILED " + e.Message);
        }
    });
    return task;
}

为了显示从独立存储的图像,然后,你可以参考我的回答中描述的方法之一在这里 。



文章来源: Download Image in Windows Phone 8