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