gpt4 book ai didi

c# - 如何使用 Dispatcher 设置 Image.Source 属性?

转载 作者:太空狗 更新时间:2023-10-29 22:14:45 24 4
gpt4 key购买 nike

我试过使用这个建议:http://msdn.microsoft.com/en-us/library/ms741870.aspx (“使用后台线程处理阻塞操作”)。

这是我的代码:

  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 属性有什么区别?我能做什么?

最佳答案

具体建议 thresholdImage 正在后台线程上创建。要么在 UI 线程上创建它,要么在创建后卡住它。

一般建议:不同之处在于 ImageSource 是一个 DependencyObject,因此它具有线程关联性。因此,您需要在与分配给它的 Image 相同的线程(即 UI 线程)上创建 ImageSource,或者您需要将 Freeze() ImageSource 一旦您创建了它,就允许任何线程访问它。

关于c# - 如何使用 Dispatcher 设置 Image.Source 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6328503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com