/img/avatar.jpg

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);

资源键Key

1. 什么是资源键

资源键x:Key用作创建和引用资源的唯一标识,作用类似于名称,常出现在ResourceDictionary中且要求必须为 ResourceDictionary 内的每项定义一个键。

如何在WPF中停止线程

1. Abort的非及时性

使用多线程经常会遇到一个问题,如何停止这个Thread?在WPF中提供了Abort方法,但MSDN却告诉我们:

线程不一定会立即中止,或者根本不中止。 如果线程在作为中止过程的一部分被调用的 finally 块中做非常大量的计算,从而无限期延迟中止操作,则会发生这种情况。