There may be such a requirement in the project, always obtain a new data information, but still does not affect the other operational functions, then the use of the thread, get new data into the thread operation, no impact on other operations, the following is a random get array of items as an example of the use of threads in WPF instance:
In the WPF Forms program, drag three button two action buttons, one Start button. Background code:
Public Delegate voidGetsetnumber ();// BOOLIscontinue =true; PublicThreadModel () {InitializeComponent (); } //Start Private voidButstart_click (Objectsender, RoutedEventArgs e) { if(iscontinue) {iscontinue=false; Button1. Content="Stop (stop)"; Button1. Dispatcher.begininvoke (Dispatcherpriority.normal,NewGetsetnumber (Getnewnumber));//asynchronous invocation with delegates } Else{iscontinue=true; Button1. Content="Continue (Continue)"; } } Private voidGetnewnumber () {string[] ss =NULL; inthour =DateTime.Now.Hour; if(Hour >=Ten&& Hour <= -) {Label1. Content="still worrying about what to eat for lunch, click to see ..."; SS=New string[]{"Noodles","Rice Noodles","Rice","Rice Bowls","Potato Flour","Fried Rice","Fried Noodles","Pie","Porridge","steamed Bun","dumplings","Small Bowl","Sand Pot","Bubble Noodles","hot and dry noodles","Hot and Sour powder","Spicy Soup" }; } Else{Label1. Content="a fair and impartial name call"; SS=New string[]{"to the star","Fruit Dew","Wang Jinlan","Helen","Jia Chin","Liu Implication","Guo Fengxi","Song","Boozie","Wang Yu","Tanju","Li Le","Zhang Sa","li Si","Wang Wu","Lucerne","Tianqi","Yang Ba","Hu Yu","Dengmu", "Zhang Hong","Wang Li","Zhenglan","y","Li Lu","Hu Ming","Xiangyang","Yang Yang","Steel Egg","Dungu", }; } //randomly take the values in an arrayRandom random =NewRandom (); intindex =Random. Next (ss. Count ()); stringNumber =Ss[index]; TextBox1.Text=Number ; //recursive call if not using thread will go into the dead loop if(!iscontinue) {button1. Dispatcher.begininvoke (System.Windows.Threading.DispatcherPriority.SystemIdle, NewGetsetnumber ( This. Getnewnumber)); } } //Action 1 Private voidButoperate1_click (Objectsender, RoutedEventArgs e) {MessageBox.Show ("I got it! "); } //Action 2 Private voidButoperate2_click (Objectsender, RoutedEventArgs e) {MessageBox.Show ("Oh, oh, oh, too ."); }
The use of threads in WPF