【问题标题】:The calling thread cannot access this object - Timer [duplicate]调用线程无法访问此对象 - Timer [重复]
【发布时间】:2013-07-31 01:21:03
【问题描述】:

我在一个间隔为1000 的方法中设置了一个Timer,这样它每秒都会在Textbox 中输入另一个相应的字符(几乎是自动输入)。当我检查 _currentTextLength == _text.Length 时,我收到线程错误“调用线程无法访问此对象,因为不同的线程拥有它。”

 public void WriteText(string Text)
    {
        timer = new Timer();

        try
        {
            _text = Text;
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed_WriteText);
            timer.Interval = 1000;
            timer.Enabled = true;
            timer.Start();
        }
        catch
        {
            MessageBox.Show("WriteText timer could not be started.");
        }
    }
    // Write Text Timer Event
    void timer_Elapsed_WriteText(object sender, ElapsedEventArgs e)
    {
        TextBoxAutomationPeer peer = new TextBoxAutomationPeer(_textBox);
        IValueProvider valueProvider = peer.GetPattern(PatternInterface.Value) as IValueProvider;

        valueProvider.SetValue(_text.Substring(0, _currentTextLength));
        if (_currentTextLength == _text.Length) // Error here
        {
            timer.Stop();
            timer = null;
            return;
        }

        _currentTextLength++;
    }

变量_text 是一个私有类变量,_currentTextLength 也是。 _textBox 不言自明。

有什么办法解决吗?

【问题讨论】:

  • 你需要在调用_text.Length之前使用dispatcher.Invoke,因为它是从另一个线程“而不​​是它创建的线程”中调用的......
  • @Moo-Juice:这是双赢形式,但原则上是一样的......
  • @H.B.,好点子 - 谢谢。
  • 那么,当您搜索错误消息时,您发现了什么以及您发现的信息有哪些不清楚的地方?

标签: c# wpf multithreading timer


【解决方案1】:

使用DispatcherTimer 而不是计时器。

集成到 Dispatcher 队列中的计时器 以指定的时间间隔和指定的优先级处理。

应该可以解决你的问题。

【讨论】:

  • 工作就像一个魅力。非常感谢。
【解决方案2】:

这仅仅意味着你试图从一个线程中访问一些 UI 元素,而不是它被创建的线程。要克服这个问题,您需要像这样访问它

this.Dispatcher.Invoke((Action)(() =>
    {
        //access it here
    }));

注意:如果要检查是否可以正常访问可以使用this

Dispatcher.CheckAccess

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2012-03-22
    • 1970-01-01
    • 2011-02-13
    • 2014-02-13
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多