C # winform multithreading (1) -- Thread class library

Source: Internet
Author: User
Windows is a multitasking system. If you are using Windows 2000 or later, you can view Program And process. What is a process? When a program starts to run, it is a process that refers to the memory and system resources used by the running programs and programs. A process is composed of multiple threads. A thread is an execution stream in the program. Each thread has its own proprietary register (Stack pointer, program counter, etc.). However Code Zones are shared, that is, different threads can execute the same function. Multithreading means that a program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks. A thread description in the. NET Framework class library, all classes related to multithreading applications are stored in the system. Threading namespace. The thread class is used to create threads, and the threadpool class is used to manage thread pools. In addition, it provides a mechanism to solve actual problems such as thread execution arrangements, deadlocks, and inter-thread communication. If you want to use multithreading in your application, you must include this class. The thread class has several crucial methods, which are described as follows: Start (): start thread sleep (INT): static method, pause the specified milliseconds of the current thread abort (): generally, this method is used to terminate a thread suspend (): This method does not terminate unfinished threads. It only suspends threads and can be recovered later. Resume (): restores the thread execution thread entry of the thread suspended by the suspend () method to let the program know what to do with this thread. in C, the thread entry is provided through the threadstart proxy (delegate). You can regard threadstart as a function pointer pointing to the function to be executed by the thread. When thread is called. after the start () method, the thread starts to execute the Functions Represented or pointed to by threadstart. Threadstate may take the following values in various cases: aborted: the thread has stopped abortrequested: the thread of the thread. the abort () method has been called, but the thread has not stopped the Background: The thread is executed in the background, with the attribute thread. isbackground-related running: The thread is running normally. Stopped: the thread has been stopped. stoprequested: The thread is being requested to stop suincluded: the thread has been suspended. (In this status, you can call resume () method re-run) suspendrequested: The thread is requesting to be suspended, but the response to unstarted is not timely: thread is not called. start () start thread running waitsleepjoin: the thread calls wait (), sleep (), or join () if the thread used in method 2 winform is blocked, you can first look at the most direct method. NET 1.0. However, please note that this method is in. NET 2.0 and later are already incorrect methods. Public partial class form1: FORM {public form1 () {initializecomponent ();} private void form1_load (Object sender, eventargs E) {thread = new thread (threadfuntion); thread. isbackground = true; thread. start ();} private void threadfuntion () {While (true) {This. textbox1.text = datetime. now. tostring (); thread. sleep (1000) ;}} this code throws an exception in vs2005 or 2008: Cross-thread operation not valid: Control 'textbox1' accessed from a thread other than the thread it was created on. this is because. NET 2.0 and later enhanced the security mechanism, and does not allow direct cross-thread access to control attributes in winform. So how can we solve this problem? Several solutions are provided below. Solution 1: Set control. checkforillegalcrossthreadcils to false when the thread is created. This code tells the compiler: in this class, we do not check whether the cross-thread call is legal (if this sentence is not added, the operation is not abnormal, it indicates that the system and the default mode are not checked ). However, this method is not advisable. We can view the definition of the checkforillegalcrossthreadcils attribute and find that it is static. That is to say, no matter where the value is modified in the project, it will take effect globally. In addition, we usually check whether cross-thread access is abnormal. If someone else in the project modifies this attribute, our solution fails and we have to adopt another solution. Solution 2 namespace testinvoker {public partial class form1: FORM {public form1 () {initializecomponent ();} private void button#click (Object sender, eventargs E) {thread = new thread (New threadstart (startsomeworkfromuithread); thread. isbackground = true; thread. start (); // startsomeworkfromuithread read (); // label1.text = "set value through another thread! ";} Private void startsomeworkfromuithread () {If (this. invokerequired) {begininvoke (New eventhandler (runsonworkerthread), null);} else {runsonworkerthread (this, null);} private void runsonworkerthread (Object sender, eventargs e) {thread. sleep (2000); label1.text = system. datetime. now. tostring () ;}} through the upstream code, we can see that the problem has been resolved. By waiting for Asynchronization, we will not always hold the control of the main thread, in this way, you can control winform multi-threaded controls without cross-thread call exceptions.

Related Article

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.