时间
初始化时间
1 2
| DateTime date1 = new System.DateTime(2020, 7, 14); DateTime myDate = new DateTime(2020, 7, 14, 14, 23, 40);
|
时间格式化
1 2 3 4 5
| DateTime dateTime = new DateTime(2020, 7, 14, 14, 23, 40); string fctime = dateTime.ToString("HH:mm:ss");
string timestr = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff"); Console.WriteLine(timestr);
|
时间戳
1 2
| TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); string timestr = Convert.ToInt64(ts.TotalMilliseconds).ToString();
|
结果类似于
1648866151124
时间戳
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public static long Timestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long timestr = Convert.ToInt64(ts.TotalMilliseconds); return timestr; }
public static long TimestampTotalSeconds() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long timestr = Convert.ToInt64(ts.TotalSeconds); return timestr; }
|
日期格式化
1
| DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff dddd");
|
可用于路径
1 2
| string timestr = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff"); Console.WriteLine(timestr);
|
结果类似于
2022-04-02-10-05-02-3485
定时任务
定时任务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| static void Main(string[] args) { System.Timers.Timer timer = new System.Timers.Timer(); timer.Enabled = true; timer.Interval = 1000; timer.Start(); timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
Console.ReadKey(); }
private static void OnTimer(object source, ElapsedEventArgs e) { Console.WriteLine("OK, test event is fired at: " + DateTime.Now.ToString()); }
|
在后台线程上运行的,不是在UI线程上运行的。
System.Timers.Timer基于线程池线程,可以通过Elapsed事件在指定的间隔触发相应的操作。
事件中如果要操作UI线程的对象,使用下面的方式,并可以指定优先级。
1 2 3 4 5 6 7 8 9
| Dispatcher.Invoke ( () => { }, DispatcherPriority.Send );
|
在C#中使用Dispatcher.Invoke调用方法时,可以设置不同的优先级,以决定该调用在UI线程中的执行顺序。
常见的优先级有以下几种:
DispatcherPriority.Send:最高优先级,该操作会立即执行并阻塞调用线程,直到操作完成。
DispatcherPriority.Normal:默认优先级,该操作会在其他所有操作之后执行。
DispatcherPriority.Background:较低优先级,该操作会延迟执行,直到UI线程处于空闲状态。
DispatcherPriority.ContextIdle:最低优先级,该操作只有在UI线程完全空闲时才会执行。
定时任务2
1 2 3 4 5
| DispatcherTimer timer = new DispatcherTimer(); timer.Tick += OnTimer; timer.Interval = new TimeSpan(0, 0, 0, 0, 1000); timer.IsEnabled = true; timer.Start();
|
停止
在UI线程上运行的。
建议只做简答的事情,否则会阻塞UI。
显示时长
1 2 3 4 5 6
| private DateTime duration = Convert.ToDateTime("2000-01-01 00:00:00"); private void OnTimer(object sender, EventArgs e) { duration = duration.AddMilliseconds(1000); TxbTime.Content = duration.ToString("HH:mm:ss"); }
|
延时执行
1 2 3 4 5 6 7 8 9 10 11
| private void PenCheck() { ShowWithIndex(3); StartRecognitionTask(); }
async Task StartRecognitionTask() { await Task.Delay(100); ZPenUtils.GetInstance().PenRecognitionStart(); }
|