I want to display the time every 5ms, and 'fff' is used in wpf to represent ms.
Why is the fff difference in the code of new TimeSpan(0, 0, 0, 0, 5); displayed result not 5? How is it calculated?
Xaml:
<Grid>
<ListBox Height="140" HorizontalAlignment="Left" Margin="18,31,0,0"
Name="listBox1" VerticalAlignment="Top" Width="308" />
<Button x:Name="btn" Click="btn_Click" Height="50" Content=" stop"/>
</Grid>
Codebehind:
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
DispatcherTimer timer = new DispatcherTimer();
public bool What { get; set; }
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Start");
timer.Interval = new TimeSpan(0, 0, 0, 0, 5);
timer.Tick += new EventHandler(dispatcherTimer_Tick);
timer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
listBox1.Items.Add(DateTime.Now.Hour.ToString() + ":" +
DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + ":"+DateTime.Now.Millisecond.ToString());
CommandManager.InvalidateRequerySuggested();
listBox1.Items.MoveCurrentToLast();
listBox1.SelectedItem = listBox1.Items.CurrentItem;
listBox1.ScrollIntoView(listBox1.Items.CurrentItem);
}
private void btn_Click(object sender, RoutedEventArgs e)
{
timer.Stop();
}
}
}
The result:
Update :
public MainWindow()
{
InitializeComponent();
DataContext = this;
CancellationTokenSource tokenSource = new CancellationTokenSource();
Task timerTask = RunPeriodically(sendRequest, TimeSpan.FromMilliseconds(num), tokenSource.Token);
}
private void sendRequest()
{
k++;
datas.Add(DateTime.Now );
}
async Task RunPeriodically(Action action, TimeSpan interval, CancellationToken token)
{
while (k<7)
{
action();
await Task.Delay(interval, token);
}
}
