In recent times, in the self-study of WPF, is a completely ignorant of the WPF novice, for the thread to modify the UI control using a delegate to make a record, to self-query also give the necessary reference:
The interface has only one RichTextBox, starting two threads on the form, calling two functions, writing the current time every 1 seconds
One interface XAML is as follows:
<window x:class="Wpfapplication1.mainwindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="Http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow"height=" -"Width="525"windowstartuplocation="Centerscreen"Loaded="window_loaded"> <Grid> <ScrollViewer> <richtextbox horizontalalignment="Stretch"margin=" A"Name="RichTextBox1"Verticalalignment="Stretch"/> </ScrollViewer> </Grid></Window>
Two open two threads when the interface is started:
1 Private voidWindow_Loaded (Objectsender, RoutedEventArgs e)2 {3 //Create thread 14Thread T1 =NewThread (NewThreadStart (T1));5 t1. Start ();6 7 //Create thread 28Thread t2 =NewThread (NewThreadStart (T2));9 T2. Start ();Ten}
Three-thread call function:
/// <summary> ///Thread 1 Call function///Add by/// </summary> Private voidT1 () { while(true) {Thread.Sleep (Timespan.fromseconds (1)); ShowMsg (string. Format ("T1 {0}", System.DateTime.Now.ToString ("YYYY-MM-DD hh:mm:ss:fff"))); } } /// <summary> ///Thread 2 Call function///Add by/// </summary> Private voidT2 () { while(true) {Thread.Sleep (Timespan.fromseconds (1)); ShowMsg (string. Format ("T2 {0}", System.DateTime.Now.ToString ("YYYY-MM-DD hh:mm:ss:fff"))); } }
Three-write front-end functions:
Private void ShowMsg (string sMsg) { this. Dispatcher.begininvoke (Dispatcherpriority.normal, (ThreadStart)delegate() { Richtextbox1.appendtext (string. Format ("{0} \ r \ n", SMSG));} );
C # WPF uses delegates to modify UI controls