从两个线程调用 WPF

发布于 2024-12-01 13:00:09 字数 783 浏览 0 评论 0原文

我尝试调用两次,然后再次从另一个对象调用。

public void Show()
{
    if (mainGrid == null)
        return;
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.BeginInvoke(new ThreadStart(delegate() { Show(); }), DispatcherPriority.Background);
        return;
    }

    mainGrid.Children.Add(rec);
    rec.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
    rec.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

    mainGrid.Children.Add(this);
    this.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
    this.VerticalAlignment = System.Windows.VerticalAlignment.Center;
}

两个对象B、C从A继承了这个函数: 当我从进程 B.show() 调用,然后从 Thread 调用 B.showStop() 和 C.show() 时,我在使用 C.show() 中的特权 main.children.Add(..) 时遇到异常 请帮我解决这个问题。

I try to invoke twice and then from anther object once more.

public void Show()
{
    if (mainGrid == null)
        return;
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.BeginInvoke(new ThreadStart(delegate() { Show(); }), DispatcherPriority.Background);
        return;
    }

    mainGrid.Children.Add(rec);
    rec.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
    rec.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

    mainGrid.Children.Add(this);
    this.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
    this.VerticalAlignment = System.Windows.VerticalAlignment.Center;
}

two objects B, C inherit this function from A:
when I call from processes B.show() then B.showStop() from Thread and C.show() I get exception on using privileged main.children.Add(..) from C.show()
please help me solve this problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

毁我热情 2024-12-08 13:00:09

我认为你应该提供有关你的问题的更多信息,例如:

  • 哪种类是A(虽然它似乎是一个UI对象)
  • 什么是rec

但是目前我认为问题可能是你正在实例化那些视觉对象不在 UI 线程中的对象:如果您在工作线程上创建一个 Button,它将具有该线程 Dispatcher,这与 UI Thread Dispatcher 不同。

我无法用如此少的信息准确地告诉您发生了什么,但我认为您正在添加两个在不同线程上创建的控件,因此两个 Add 之一会给您一个例外。

I think you should provide more info on you problem, for example:

  • which kind of class is A (it seems to be an UI object though)
  • what is rec

But for the moment i think the problem could be that you're instantiating those visual objects not in the UI Thread: if you create say a Button on a workerthread it will have that thread Dispatcher, which is different from the UI Thread Dispatcher.

I can't exactly tell you what's happening with so little info but i think that you're adding two controls which were created on different threads so one of the two Add will give you an exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文