【问题标题】:Retrieving info from main GUI thread [duplicate]从主 GUI 线程检索信息 [重复]
【发布时间】:2015-09-08 12:09:10
【问题描述】:

我正在尝试检索 Ellipse 的 X 和 Y 坐标。检索是通过 Timer 和 EllapsedEventHandler 完成的:

public void record(object sender, ElapsedEventArgs args)
    {

        DateTime t = args.SignalTime; // Take the time the tick was done
        Point ellipseCoordiante = new Point(Canvas.GetLeft(observee.StimulyEllipse1), Canvas.GetTop(observee.StimulyEllipse1));  // Parse coordinates from StimulyWindow to service and then to thread where they will be recorded into the log file
        Point controller1 = new Point(Canvas.GetLeft(observee.Pointer1), Canvas.GetTop(observee.Pointer1));
        Point controller2 = new Point(Canvas.GetLeft(observee.Pointer2), Canvas.GetTop(observee.Pointer2));
        string[] toWrite = new string[] { t.Ticks.ToString(), " ", watch.Elapsed.ToString(), " ", ellipseCoordiante.ToString(), " ", controller1.ToString(), " ", controller2.ToString() };

        System.IO.File.WriteAllLines(logPath, toWrite);

    }

我的问题是我无法从 GUI 中检索坐标。

我收到错误消息

“调用线程无法访问此对象,因为不同的线程拥有它”。

我正在考虑每次修改 Ellipse 时将其坐标保存在不同的类中,并且 Timer 可以定期访问这些值以读取它们。

我的问题是:

a) 有没有办法直接从 GUI 线程获取我需要的信息;

b) 如果不是,那么我如何将 Canvas 中的 Ellipse x 和 y 位置传递给我制作的类

【问题讨论】:

  • 你用的是什么 Timer 类?
  • 是的,只需使用DispatcherTimer
  • 我正在使用 System.Timers.Timer 。
  • 您不会从 WPF 的 UI 中“检索信息”。相反,您创建一个可以从任何线程操作的适当数据模型,而无需理会 UI。请参阅我在重复问题中的回答,以了解如何在多线程场景中正确使用 WPF UI。

标签: wpf multithreading user-interface


【解决方案1】:

您可以使用窗口的 Dispatcher 属性并调用 Invoke 方法从 GUI 线程运行操作

【讨论】:

  • 是的,我现在正在这样做。我的问题是如何调用 Dispatcher 的方法来进一步传递信息。 Ellipse 的大小没有改变,我似乎找不到任何其他用于 Positon changind 的事件..
  • 如果你在你的 record(object sender, ElapsedEventArgs args) 方法中使用带有 Dispatcher.Invoke 的 lambda 函数,你可以在一些局部变量中设置属性的值并在 lambda 之后使用它们跨度>
猜你喜欢
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多