调用线程无法访问此对象-计时器 [英] The calling thread cannot access this object - Timer
问题描述
我正在以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屋!