2011-06-13 90 views
5

我试过使用这个推荐:http://msdn.microsoft.com/en-us/library/ms741870.aspx(“使用后台线程处理阻塞操作”)。如何使用Dispatcher设置Image.Source属性?

这是我的代码:“由于调用线程,因为不同的线程拥有它无法访问该对象”

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      ; 
     } 

     private void Process() 
     { 
      // some code creating BitmapSource thresholdedImage 

      ThreadStart start =() => 
      { 
       Dispatcher.BeginInvoke(
        System.Windows.Threading.DispatcherPriority.Normal, 
        new Action<ImageSource>(Update), 
        thresholdedImage); 
      }; 
      Thread nt = new Thread(start); 
      nt.SetApartmentState(ApartmentState.STA); 
      nt.Start(); 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      button1.IsEnabled = false; 
      button1.Content = "Processing..."; 

      Action action = new Action(Process); 
      action.BeginInvoke(null, null); 
     } 

     private void Update(ImageSource source) 
     { 
      this.image1.Source = source; // ! this line throw exception 

      this.button1.IsEnabled = true; // this line works 
      this.button1.Content = "Process"; // this line works 
     } 
    } 

在它抛出InvalidOperationException异常标记线。但是如果我删除这一行,应用程序就可以工作

XAML: 
<!-- language: xaml --> 
    <Window x:Class="BlackZonesRemover.MainWindow" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:my="clr-namespace:BlackZonesRemover" 
      Title="MainWindow" Height="600" Width="800" Loaded="Window_Loaded"> 
     <Grid> 
      <Grid.RowDefinitions> 
       <RowDefinition /> 
       <RowDefinition Height="Auto" /> 
      </Grid.RowDefinitions> 
      <Border Background="LightBlue"> 
       <Image Name="image1" Stretch="Uniform" /> 
      </Border> 
      <Button Content="Button" Grid.Row="1" Height="23" Name="button1" Width="75" Margin="10" Click="button1_Click" /> 
     </Grid> 
    </Window> 

Image.Source属性和Button.IsEnabled和Button.Content属性有什么区别?我能做什么?

回答

10

具体建议:thresholdImage正在后台线程上创建。可以在UI线程上创建它,或者在创建后冻结它。

一般的建议:所不同的是,ImageSourceDependencyObject所以它具有线程亲和力。因此,您需要在与其分配的Image(即UI线程)相同的线程上创建ImageSource,或者一旦创建它就需要Freeze()ImageSource,从而允许任何线程访问它。

+0

谢谢。现在它起作用了,现在我明白了 – 2011-06-13 13:41:55

相关问题