There are many methods for multi-threaded access controls on the Internet. Here, I only use this method. Other methods can be searched on the Internet.
First declare a global variable and a delegate type (used to access the control)
01.PrivateBackgroundworker _ bworker;
02.Delegate VoidSetprogressbardelegate (IntValue );
Assign some attributes to this workfer in a button event.
01. _ bworker = new backgroundworker (); 02. _ bworker. dowork + = new doworkeventhandler (bworker_dowork); 03. _ bworker. workerreportsprogress = true; 04. _ bworker. workersuppscanscancellation = true; 05. 06. _ bworker. runworkerasync (); 07. _ bworker. progresschanged + = delegate (Object S, progresschangedeventargs ex) 08. {09. if (probarstate. invokerequired) 10. {11. Setprogressbardelegate setprogressbar = new setprogressbardelegate (delegate (INT value) 12. {13. probarstate. value = ex. progresspercentage; 14.}); 15. This. Invoke (setprogressbar ); 16 .} 17. else 18. {19. probarstate. value = ex. progresspercentage; 20 .} 21 .}; 22. _ bworker. runworkercompleted + = delegate (Object S, runworkercompletedeventargs ex) 23. {24. 25. 26. if (ex. cancelled) 27. {28. lblstate. TEXT = "DD"; 29. probarstate. value = 0; 30 .} 31. else 32. {33. lblstate. TEXT = "SS"; 34 .} 35 .};
01. void bworker_dowork (Object sender, doworkeventargs e) 02. {03. 04. // function to do work 05. if (_ bworker. cancellationpending) 06. {07. e. cancel = true; 08 .} 09 .}
The aboveCodeThe most important part is the red-letter this. Invoke (setprogressbar); this sentence means winfrom ApplicationProgramThe main thread (the thread that creates the control) to assign values to the control. This indicates the main thread.
Invokerequired: Get a value indicating whether the caller must call the invoke method when calling the control method, because the call orientation is in a thread other than the thread where the control is created. That is to say, if the control is located outside the control creation thread (main thread), you need to use the invoke method to push the control operation method to the appropriate thread (main thread) for execution.
Another global attribute is set (I forgot to avoid detecting the security of the Cross-thread access control. It is a global attribute, and the other attributes are set in one place, it is easy to issue bugs in other places where security needs to be checked.) That is not desirable.