所以我是新來的定時器和線程,我找不到如何使一個計時器,調用一個函數,編輯/修改我的MainWindow上的控件。如何使用System.Timers.Timer訪問/修改另一個線程上的控件?
XAML代碼:
<Window x:Class="TimerTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="479" />
</Grid>
</Window>
C#代碼:
namespace TimerTest
{
public partial class MainWindow : Window
{
//Declaring my aTimer as global
public static System.Timers.Timer aTimer;
//Function that is called
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
textBox1.Text += "SomeText ";
}
public MainWindow()
{
InitializeComponent();
aTimer = new Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000; // every 5 seconds
aTimer.Enabled = true;
}
}
}
的錯誤,我得到: 「因爲不同的線程擁有它調用線程不能訪問此對象。」 P.S .:另外我對代表不太好,所以如果你認爲在這種情況下可以幫助我,那麼請發佈代碼示例。
類似:http://stackoverflow.com/questions/4115598/controls-and-threads/4115634#4115634 – davisoa 2012-03-02 20:26:25
爲什麼在System.Windows.Forms.Timer時使用此線程計時器類來訪問可視化控件? – 2012-03-02 20:36:16
@davisoa:Bleah,我很討厭那些使用遞歸更新方法的代碼片段。總是需要我花5分鐘來了解發生了什麼。 – Tudor 2012-03-02 20:45:47