2011-06-13 5 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을 생성해야합니다. 그렇지 않으면 어떤 스레드 가든 액세스 할 수 있도록 ImageSource을 작성하면 Freeze()이 필요합니다. 그것.

+0

을 참조하십시오. 이제 효과가 있으며 이제는 요점을 얻었습니다. –

관련 문제