1---线程
(1)创建线程------》 其中threading 要放到窗口加载事件 中
AutoResetEvent _auto = new AutoResetEvent(false); bool _isstop = true; //默认线程是关闭的,等待执行的! public void threading() { Thread _thread = new Thread(new ParameterizedThreadStart((obj) => { while(true) { if (_isstop) _auto.WaitOne(); //设置为线程为等待状态 this.Dispatcher.Invoke(() => { try {
//进行的操作 } catch(Exception) { } }); Thread.Sleep(300); } })) { IsBackground = true}; _thread.Start(); }
(2)启动-暂停
if (this.btnSearch.Content.ToString() == "查询") { _isstop = false; _auto.Set(); this.btnSearch.Content = "停止"; } else { _isstop = true; _auto.Reset(); this.btnSearch.Content = "查询"; }
(3)可以这样用(通过_isStop = false;)来启动线程 MyThreading放到//窗口加载事件 中
private void MyThreading() { _thread = new Thread(new ParameterizedThreadStart((obj) => { while (true) { this.Dispatcher.Invoke(() => { if (!_isStop) { //操作 } }); Thread.Sleep(12000); //用于LED显示的时间 加载完 } })) { IsBackground = true }; _thread.Start(); }
2---定时器
(1)创建定时器
DispatcherTimer tm = new DispatcherTimer(); private void tm_Tick(object sender, EventArgs ee) {
//需要执行的操作 }
(2)启动定时器
private void btnOpen_Click(object sender, RoutedEventArgs e) { tm.Tick += new EventHandler(tm_Tick); tm.Interval = TimeSpan.FromSeconds(1); //定时的时间间隔 tm.Start(); } //tm.Stop();//关闭定时器
//tm.Tick +=tm_Tick; 等同