私は新しいasync/await
キーワードを使用してSystem.Threading.Tasks
名前空間をお勧めします。
// The `onTick` method will be called periodically unless cancelled.
private static async Task RunPeriodicAsync(Action onTick,
TimeSpan dueTime,
TimeSpan interval,
CancellationToken token)
{
// Initial wait time before we begin the periodic loop.
if(dueTime > TimeSpan.Zero)
await Task.Delay(dueTime, token);
// Repeat this loop until cancelled.
while(!token.IsCancellationRequested)
{
// Call our onTick function.
onTick?.Invoke();
// Wait to repeat again.
if(interval > TimeSpan.Zero)
await Task.Delay(interval, token);
}
}
次に、あなただけのどこかに、このメソッドを呼び出します。
private void Initialize()
{
var dueTime = TimeSpan.FromSeconds(5);
var interval = TimeSpan.FromSeconds(5);
// TODO: Add a CancellationTokenSource and supply the token here instead of None.
RunPeriodicAsync(OnTick, dueTime, interval, CancellationToken.None);
}
private void OnTick()
{
// TODO: Your code here
}
OK私はMainwindow.xaml.cs mainメソッドでこれを書き込みます。子ウィンドウを開いてもこのタイマーがチェックされますか?または、アプリケーションのメインウィンドウや子ウィンドウのどこにいても、このコードを置くのに最適な場所は何ですか? –
@sateeshmunagalaタイマーを使用している間にコンテナクラスが破棄されていないかぎり、それを配置するコンテキストは関係ありません。 – Mir