WPF中使用Free解决访问非UI线程创建的对象抛出的Thread异常
来源:互联网 发布:那个数据库软件最好 编辑:程序博客网 时间:2024/05/29 04:35
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.Threading;using System.Windows.Threading;namespace WpfMultiThread{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { class WasImage { public BitmapSource bmp = null; } public MainWindow() { InitializeComponent(); } private double BoodWidth = 0; private void Window_Loaded(object sender, RoutedEventArgs e) { BoodWidth = m_rectBood.Width; } private double counter = 1; private delegate void NormalDelegate(); private WasImage Cal() { WasImage wasImg = new WasImage(); wasImg.bmp = new BitmapImage(new Uri(System.Environment.CurrentDirectory + "\\zz.jpg")); wasImg.bmp.Freeze();//如果没有此步则在UI线程中调用会失败 return wasImg; } private void UpdateUI() { m_rectBood.Width = counter * BoodWidth; //m_tblCounter.Text = counter.ToString(); } private void m_btnStart_Click(object sender, RoutedEventArgs e) { //异步任务封装在一个delegate中, 此delegate将运行在后台线程 Func<WasImage> asyncAction = this.Cal; //在UI线程中得到异步任务的返回值,并更新UI //必须在UI线程中执行 Action<IAsyncResult> resultHandler = delegate(IAsyncResult asyncResult) { WasImage wasImage = asyncAction.EndInvoke(asyncResult); m_imgtest.Source = wasImage.bmp; }; //异步任务执行完毕后的callback, 此callback运行在后台线程上. //此callback会异步调用resultHandler来处理异步任务的返回值. AsyncCallback asyncActionCallback = delegate(IAsyncResult asyncResult) { this.Dispatcher.BeginInvoke(DispatcherPriority.Background, resultHandler, asyncResult); }; //在UI线程中开始异步任务, //asyncAction(后台线程), asyncActionCallback(后台线程)和resultHandler(UI线程) //将被依次执行 asyncAction.BeginInvoke(asyncActionCallback, null); //NormalDelegate calDele = new NormalDelegate(Cal); //calDele.BeginInvoke(null, null); } private void m_btnInvoke_Click(object sender, RoutedEventArgs e) { //m_imgtest.Source = (this.Tag as WasImage).bmp; } }}