Security update control across threads

Source: Internet
Author: User

write down a Safecall method in the extension method class in your project:usingSystem;usingSystem.Windows.Forms;namespacewindowsformsapplication1{ Public Static classExtensions { Public Static voidSafecall ( ThisControl CTRL, Action callback) {            if(CTRL. invokerequired) Ctrl.            Invoke (callback); Elsecallback (); }} It just takes the code you want to protect as a callback. Then any place that needs to protect some code can be called:usingSystem;usingSystem.Threading;usingSystem.Windows.Forms;namespacewindowsformsapplication1{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); }         Private voidForm1_Load (Objectsender, EventArgs e) {ThreadPool.QueueUserWorkItem (H=            {                 for(vari =0; I <10000000; i++) {Label1. Safecall (()={Label1. Text=i.tostring ();                    }); Thread.Sleep ( -);        }            }); }     }}
of course, using LAMDA is one of my "bad problems". You can actually use the traditional anonymous delegate notation:usingSystem;usingSystem.Threading;usingSystem.Windows.Forms;namespacewindowsformsapplication1{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); }         Private voidForm1_Load (Objectsender, EventArgs e) {ThreadPool.QueueUserWorkItem (H=            {                 for(vari =0; I <10000000; i++) {Label1. Safecall (Delegate() {Label1. Text=i.tostring ();                    }); Thread.Sleep ( -);        }            }); }     }}

Security update control across threads

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.