Vla*_* M. 3 c# user-interface controls multithreading timer
所以我是计时器和线程的新手,我无法找到如何制作一个调用编辑/修改我的MainWindow控件的函数的计时器.
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;
        }
    }
}
我得到的错误:"调用线程无法访问此对象,因为另一个线程拥有它." PS:另外我对代表不太好,所以如果你认为在这种情况下可以帮助我,那么请发一个代码示例.
Pet*_*art 13
只需添加:
aTimer.SynchronizingObject = this;
创建计时器后,或使用ToolBox-> Components中的OTHER类型的计时器,即System.Windows.Forms.Timer.
您当前正在使用的计时器触发线程池线程而不是UI线程,因此需要与UI线程同步以按您希望的方式工作.
| 归档时间: | 
 | 
| 查看次数: | 9646 次 | 
| 最近记录: |