调用线程无法访问此对象-计时器 [英] The calling thread cannot access this object - Timer

查看:79
本文介绍了调用线程无法访问此对象-计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以1000为间隔的方法中设置一个Timer,以便每秒钟它将在Textbox中键入另一个对应的字符(几乎是自动键入).当我检查_currentTextLength == _text.Length时,出现线程错误调用线程无法访问该对象,因为其他线程拥有它."

I am setting up a Timer within a method with an interval of 1000 so that every second it will type another corresponding character into a Textbox (pretty much automating typing). When I check for _currentTextLength == _text.Length I get the threading error "The calling thread cannot access this object because a different thread owns it."

 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不言自明.

The variable _text is a private class variable and so is _currentTextLength. _textBox is self explanatory.

有什么办法解决这个问题?

Any way to solve this?

推荐答案

使用 DispatcherTimer 而不是计时器.

集成到Dispatcher队列中的计时器 按指定的时间间隔和指定的优先级进行处理.

A timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority.

应该解决您的问题.

这篇关于调用线程无法访问此对象-计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆