项目中可能会有这样的需求,一直获取新的某个数据信息,但仍不影响其他的操作功能,这时就用到了线程,获取新数据放到线程中操作,对其他操作不产生影响,下面就以随机获取数组中项为例解说WPF中使用线程这一实例:
在WPF窗体程序中拖三个Button 两个操作按钮,一个启动按钮。后台代码:
public delegate void GetSetNumber();// bool IsContinue = true; public ThreadModel() { InitializeComponent(); } //启动 private void butStart_Click(object sender, RoutedEventArgs e) { if (IsContinue) { IsContinue = false; button1.Content = "停止(Stop)"; button1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new GetSetNumber(GetNewNumber));//利用委托异步调用 } else { IsContinue = true; button1.Content = "继续(Continue)"; } } private void GetNewNumber() { string[] ss = null; int hour = DateTime.Now.Hour; if (hour >= 10 && hour <= 13) { label1.Content = "还在为中午吃什么发愁吗,来点击看看……"; ss = new string[]{"面条","米线","米饭", "盖饭", "土豆粉" ,"炒饭", "炒面", "饼","粥","包子","饺子","小碗","砂锅", "泡面", "热干面" ,"酸辣粉", "麻辣烫" }; } else { label1.Content = "公平公正的点名"; ss = new string[]{ "向颗","果露","王金兰", "贺玲", "贾群" ,"刘蕴涵", "郭凤熙", "宋经曌","布茜","王玉","单茹","李兒","张萨", "李思", "王武" ,"兰琉", "田琪", "杨霸","胡玖","邓穆", "张红","王丽","郑兰", "郭青", "李路" ,"胡明", "襄阳", "杨洋","钢蛋","邓古", }; } //随机取数组中的值 Random random = new Random(); int index = random.Next(ss.Count()); string number = ss[index]; textBox1.Text = number; //递归调用若不使用线程将进入死循环 if (!IsContinue) { button1.Dispatcher.BeginInvoke( System.Windows.Threading.DispatcherPriority.SystemIdle, new GetSetNumber(this.GetNewNumber)); } } //操作1 private void butOperate1_Click(object sender, RoutedEventArgs e) { MessageBox.Show("我弹出来了!"); } //操作2 private void butOperate2_Click(object sender, RoutedEventArgs e) { MessageBox.Show("噢噢噢也"); }
时间: 2024-11-05 02:27:51