System.Threading.Timer クラスは、スレッドを使用することを理解して使用できます (以下を参照)。タイマーはコンストラクターで設定されます。すぐに開始し (3 番目のパラメーターを 0 に設定)、1000 ミリ秒ごとに実行します (4 番目のパラメーター)。内部では、コードは Dispatcher をすぐに呼び出して UI を更新します。これの潜在的な利点は、別のスレッドで実行できるビジーな作業のために UI スレッドを拘束しないことです (たとえば、BackgroundWorker を使用せずに)。
using System.Windows.Controls;
using System.Threading;
namespace SLTimers
{
public partial class MainPage : UserControl
{
private Timer _tmr;
private int _counter;
public MainPage()
{
InitializeComponent();
_tmr = new Timer((state) =>
{
++_counter;
this.Dispatcher.BeginInvoke(() =>
{
txtCounter.Text = _counter.ToString();
});
}, null, 0, 1000);
}
}
}
<UserControl x:Class="SLTimers.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="txtCounter" Margin="12" FontSize="80" Text="0"/>
</Grid>
</UserControl>