目录

WPF异步加载BitmapImage

目录

在WPF中异步获取HTTP图片并赋值给Image控件,遇到诸多问题,如多线程队列,资源不释放等,最终琢磨出下面的方式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
Uri uri = e.Argument as Uri;

using (WebClient webClient = new WebClient())
{
	webClient.Proxy = null; 
	webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
	try
	{
		byte[] imageBytes = null;

		imageBytes = webClient.DownloadData(uri);

		if (imageBytes == null)
		{
			e.Result = null;
			return;
		} 
		MemoryStream imageStream = new MemoryStream(imageBytes);
		BitmapImage image = new BitmapImage();

		image.BeginInit();
		image.StreamSource = imageStream;
		image.CacheOption = BitmapCacheOption.OnLoad;
		image.EndInit();

		image.Freeze();
		imageStream.Close();

		e.Result = image;
	}
	catch (WebException ex)
	{
		e.Result = ex;
	}
}
};

worker.RunWorkerCompleted += (s, e) =>
{
	BitmapImage bitmapImage = e.Result as BitmapImage;
	if (bitmapImage != null)
	{
		myImage.Source = bitmapImage;
	}
	worker.Dispose();
};

worker.RunWorkerAsync(imageUri);