A simple way for WPF to update the UI interface in a background thread

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.