【发布时间】:2011-07-21 14:13:21
【问题描述】:
在哪里可以找到类似于 WPF 中的 C# Timer 控件的控件?
【问题讨论】:
在哪里可以找到类似于 WPF 中的 C# Timer 控件的控件?
【问题讨论】:
通常的 WPF 计时器是DispatcherTimer,它不是控件而是在代码中使用。它与 WinForms 计时器的工作方式基本相同:
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
有关 DispatcherTimer 的更多信息,请访问here
【讨论】:
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
使用 Dispatcher,您需要包含
using System.Windows.Threading;
还请注意,如果您右键单击 DispatcherTimer 并单击 Resolve,它应该添加适当的引用。
【讨论】:
你也可以使用
using System.Timers;
using System.Threading;
【讨论】:
定时器有特殊功能。
如果你使用StartAsync ()或Start (),线程不会阻塞用户界面元素
namespace UITimer
{
using thread = System.Threading;
public class Timer
{
public event Action<thread::SynchronizationContext> TaskAsyncTick;
public event Action Tick;
public event Action AsyncTick;
public int Interval { get; set; } = 1;
private bool canceled = false;
private bool canceling = false;
public async void Start()
{
while(true)
{
if (!canceled)
{
if (!canceling)
{
await Task.Delay(Interval);
Tick.Invoke();
}
}
else
{
canceled = false;
break;
}
}
}
public void Resume()
{
canceling = false;
}
public void Cancel()
{
canceling = true;
}
public async void StartAsyncTask(thread::SynchronizationContext
context)
{
while (true)
{
if (!canceled)
{
if (!canceling)
{
await Task.Delay(Interval).ConfigureAwait(false);
TaskAsyncTick.Invoke(context);
}
}
else
{
canceled = false;
break;
}
}
}
public void StartAsync()
{
thread::ThreadPool.QueueUserWorkItem((x) =>
{
while (true)
{
if (!canceled)
{
if (!canceling)
{
thread::Thread.Sleep(Interval);
Application.Current.Dispatcher.Invoke(AsyncTick);
}
}
else
{
canceled = false;
break;
}
}
});
}
public void StartAsync(thread::SynchronizationContext context)
{
thread::ThreadPool.QueueUserWorkItem((x) =>
{
while(true)
{
if (!canceled)
{
if (!canceling)
{
thread::Thread.Sleep(Interval);
context.Post((xfail) => { AsyncTick.Invoke(); }, null);
}
}
else
{
canceled = false;
break;
}
}
});
}
public void Abort()
{
canceled = true;
}
}
}
【讨论】: