gpt4 book ai didi

c# - 线程无法访问对象

转载 作者:行者123 更新时间:2023-11-30 13:48:51 24 4
gpt4 key购买 nike

我声明了一个字段:

WriteableBitmap colorBitmap;

然后我创建了一个简单的线程来做一些事情:

private void doSomething()
{
// ... bla bla bla
colorBitmap = new WriteableBitmap(/* parameters */);
myImage.Source = colorBitmap; // error here:S
}

在 Windows_Loaded 事件中,我声明并启动了一个新线程:

private void window_Loaded(object sender, RoutedEventArgs e)
{
Thread th = new Thread(new ThreadStart(doSomething));
th.Start();
}

问题是我无法更改 myImage 的来源。我遇到了如下错误:

InvalidOperationException was unhandled The calling thread cannot access this object because a different thread owns it.

我尝试使用 Dispatcher.Invoke,但没有帮助...

Application.Current.Dispatcher.Invoke((Action)delegate
{
myImage.Source = colorBitmap;
});

我一直在寻找一些答案,但从未找到与我完全一样的情况。任何人都可以帮助我理解如何解决这样的问题(我最近遇到了同样的问题,但我无法调用该方法,因为其他线程拥有它)。

最佳答案

您的代码有两个问题:

  1. 您不能从不同于创建它的线程的另一个线程访问 WriteableBitmap。如果您想这样做,您需要先调用 WriteableBitmap.Freeze()

  2. 来卡住您的位图
  3. 您不能在非调度程序线程的线程中访问 myImage.Source

这应该可以解决这两个问题:

private void doSomething()
{
// ... bla bla bla
colorBitmap = new WriteableBitmap(/* parameters */);
colorBitmap.Freeze();
Application.Current.Dispatcher.Invoke((Action)delegate
{
myImage.Source = colorBitmap;
});
}

编辑请注意,此方法允许您在线程中的任意位置创建和更新位图。一旦位图被卡住,就不能再修改,在这种情况下,您应该将其丢弃并创建一个新的。

附带说明,如果您不希望阻止线程更新 myImage.Source,请使用 BeginInvoke 而不是 Invoke

关于c# - 线程无法访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11226806/

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