The WPF framework stipulates that only the UI thread (the main thread) can update the interface, and all other background threads cannot update the interface directly. Fortunately, the SynchronizationContext classes provided by WPF and the lambda Expressions of C # provide a convenient workaround. Here's the code:
public static SynchronizationContext s_sc = Synchronization.current; Static members of the main window class in the App class: static Thread S_mainthread = Thread.CurrentThread; This variable holds the main thread (UI thread) for the following property service//This property represents whether the current thread of execution is running public static bool Isruninmainthread {get {return} in the main thread Thread.CurrentThread = = S_mainthread;}} This function is used to set an element on the UI interface public void SetText (string strText) {if (! App.isruninmainthread) {s_sc. Post (oo = {SetText (strText);}, NULL); You can use post or send return; } Textblock1.text = StrText;} This function is used to get the content from the UI interface elements public string GetText () {if (! App.isruninmainthread) {string str = NULL; S_sc. Send (oo = {str = GetText ();}, NULL); //
You have to use Sendreturn str; } return textblock1.text;} Both the GetText and settext functions are not problematic either in the main thread or in the background threads.
A simple way for WPF to update the UI interface in a background thread