通过此链接提出问题并尝试实施已接受的答案:
Invoking a method asynchronously and/or on its own thread to increase performance
我正在尝试使用名为DownloadImageFromUrl的简单方法,该方法接受字符串Url并将Bitmap返回到将使用async运行的方法。目前的方法:
private Bitmap DownloadImageFromUrl(string url)
{
//// METHOD A:
//WebRequest request = System.Net.WebRequest.Create(url);
//WebResponse response = request.GetResponse();
//Stream responseStream = response.GetResponseStream();
//return new Bitmap(responseStream);
// METHOD B:
using (WebClient client = new WebClient())
{
byte[] data = client.DownloadData(url);
using (MemoryStream mem = (data == null) ? null : new MemoryStream(data))
{
return (data == null || mem == null) ? null : (Bitmap)Image.FromStream(mem);
}
}
}
制作这个异步的想法是这样的,在另一种方法中,我可以用这个做这样的事情:
public async Task<HttpResponseMessage> process(string image)
{
var task = DownloadFromBlobAsync(image);
var setupData = DoSomeSetup();
var image = await task;
return DrawTextOnImage(image, setupData);
}
DoSomeSetup需要相当长的时间并且下载图像也是如此,所以我想在设置发生时在自己的线程上下载图像。
我不确定有哪些工具可用于更改此downloadImageFromUrl以返回任务..任何资源或代码示例都会有所帮助。
答案 0 :(得分:0)
来自charlie的How to download image from url using c#示例:
using (WebClient client = new WebClient())
{
client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
}
EDITED
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile("fileNameHere");
BitmapImage bitmap = new BitmapImage();
var stream = await DownloadFile(new Uri("http://someuri.com", UriKind.Absolute));
bitmap.SetSource(stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
可能重复: