我只想在另一个线程中更改窗口的背景。有两个程序,一个是工作正确的,另一个抛出InvalidOperationException。使用由其他线程创建的对象
权代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Thread t = new Thread(new ParameterizedThreadStart(threadTest));
t.Start(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");
}
void threadTest(object obj)
{
string path = obj as string;
this.Dispatcher.Invoke(new Func<object>(() => this.Background = new
}
}
的错误代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Thread t = new Thread(new ParameterizedThreadStart(threadTest));
t.Start(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");
}
void threadTest(object obj)
{
string path = obj as string;
//this.Dispatcher.Invoke(new Func<object>(() => this.Background = new ImageBrush(new BitmapImage(new Uri(path)))));
ImageBrush background = new ImageBrush(new BitmapImage(new Uri(path)));
this.Dispatcher.Invoke(new Func<object>(() => this.Background = background));
}
}
不同,这些代码之间是,错误代码创建的子线程的图像刷对象。 所以我的问题是:在wpf程序中,线程是否只能使用由自己的线程创建的对象? 感谢您的任何答复。
如果UI线程只能使用自己创建的对象,是否有任何方法让其他线程通过对象到UI线程? – adream307 2012-04-21 06:17:51
@ adream307当然有,请参阅我的编辑:) – 2012-04-21 14:28:46