2011-06-13 92 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

相關問題