. Net Winform Development notes (1)

Source: Internet
Author: User

1. Understand the difference between the main method in the Program. cs file in the "Windows Forms Application" project and the main method in the traditional C ++ Console Program. At the program running level, there is no difference between the two. They are both program entry points and are the first thread in the process. The former hides the message loop required by the UI application, while the latter does not.

2. Each Windows desktop application must contain at least one UI thread. The so-called UI thread is the thread that can respond to Windows messages. Generally, a Windows desktop application contains only one UI thread unless otherwise required.

3. the UI thread is essentially the same as a common thread. It is generally the Program's entry thread, such as Program. the main method in the cs file is the UI thread, and Application. the Run () method encapsulates the message loop. If there is no Application. Run () method, it is exactly the same as other threads. It is called a UI thread because it contains a similarCopy codeThe Code is as follows: While (GetMessage (...)) // Retrieve Windows Message
{
// Process windows messages and call the callback method compiled by the developer, such as the event processing program.
}

.
4. For more information about the Windows message mechanism, visit Google or Baidu.

5. UI threads are mainly responsible for real-time interface updates. Therefore, when writing code, observe the following rules:
1) do not write (or call) time-consuming code blocks in the event processing program of the control;
2) do not call the blocking method in the event handler of the control;

6. Understand the differences between the delegate, event, and event handler in the program design.Copy codeThe Code is as follows: 1) Publicdelegate void KeyPressEventHandler (KeyPressEventArgse );
2) Public eventKeyPressEventHandler KeyPress;
3) Public void Textbox1_KeyPress (objectsender, KeyPressEventArgs e)
{
//....
}

Where:
1 is delegate 2 is event 3 is event handler

7. all event handlers are called in the UI thread, because the UI thread is responsible for updating the interface, therefore, the UI thread must always be smooth (the while LOOP body in 3 cannot take too long), that is, it cannot be returned if a method is executed for a long time. Therefore, observe the rules in step 5.

8. The same method can run in multiple threads. There is no one-to-one principle between methods and threads.Copy codeThe Code is as follows: Private void thread_pro ()//
{
}
1) privatebutton1_click (object sender, EventArgs e)
{
Thread_pro (); // thread_pro runs in the UI thread
}
2) private button#click (object sender, EventArgs e)
{
Thread t = new Thread (newThreadStart (thread_pro ));
Thread t1 = new Thread (new ThreadStart (thread_pro ));
Thread t2 = newThread (new ThreadStart (thread_pro ));
T. start (); // thread_pro runs in t thread
T1.start (); // thread_pro runs in t1 thread
T.2.start (); // thread_pro runs in the t2 thread
}

3) You can also ship the method to the thread that creates the Control by using the Control. Invoke () or BenginInvoke method.
In all the above cases, please note that the thread shares data.

9. Pay attention to the "thread security" issue in multi-threaded programming. For objects with "non-Atomic" operations, measures must be taken to avoid errors.

The UI controls (buttons, datagridview, and so on) and collections (List, ArrayList) belong to such objects. The controls cannot be accessed by multiple threads at any time.

10. resolutely put an end to cross-thread access to the UI control. For the reason, see 9. For methods for cross-thread control access, see 3 in 8 ).

11. except. the event handler in Net Winform is called in the UI thread, and almost all other callback methods are not executed in the UI thread. Therefore, when developers compile the callback method, follow the rules 9 and 10.

12. Understand what the callback method is. The callback method is generally compiled by the developer, but not called by the developer. It is called by the system (or framework. During the development of Windows desktop applications, the event handler of the control is a callback method. The callback method is generally used in the "Observer" design mode. When an event is triggered by the event initiator, it will call the callback method. All events of the control belong to this class.
Another common method is to execute an operation asynchronously, for example, AsyncCallBack type parameter in socket. BeginAccept.
In the era of rampant frameworks, the code written by developers generally belongs to the callback code. Because the main structure of the program is integrated by the predecessors in the framework. Developers only need to complete the vacant part like filling in the blanks.

13. Blocking means that methods cannot be returned in time because they contain time-consuming operations.
There is no absolute limit between "timely" and "non-timely", for example:Copy codeThe Code is as follows: int func1 () // return in time
{
Int index = 0;
For (int I = 0; I <100; I ++)
{
Index ++;
}
Return index;
}
Int func2 () // non-timely return
{
Int index = 0;
For (int I = 0; I <1000; I ++)
{
For (int j = 0; j <1000; ++ j)
{
Index ++;
}
}
Return index;
}

The above func1 is a non-blocking method, and func2 is a blocking method.

14. Windows Forms applications do not directly interact with hardware devices such as the keyboard and mouse. They only interact directly with Windows messages. Although on the surface, the mouse, keyboard, and other hardware devices operate on the form, in essence, the desktop applications you write do not understand every action of these hardware devices. They bridge through the Operating System (driver). The operating system first translates every action of the hardware device into a windows message (a data structure that can be understood by the Program ), then, the program can understand and respond accordingly.
15. The so-called "blocking call thread" refers to calling the blocking method in a thread, so that the thread cannot execute subsequent code in time.Copy codeThe Code is as follows: Void func ()
{
Int index = 0;
For (int I = 0; I <10000; ++ I)
{
For (int j = 0; j <10000; ++ j)
{
I ndex ++;
}
}
}
Thread t = newThread (new ThreadStart (func ));
T. Start (); // The blocking method func is called in thread t, so thread t will be blocked.

When introducing the func method, you can describe it as follows: This method will block the calling thread.

16. the same method can be called by multiple threads. It can be called by both the UI thread and non-UI thread. How can I write access the UI control (UI element) IN THE METHOD body) what about the code? (Cross-thread access to the UI control will cause an exception)Copy codeThe Code is as follows: Void func ()
{
Textbox1.Text = "test ";
PictureBox1.Image = Image.FromFile(“a.jpg ");
}

1) The above func method may run in the UI thread, as follows:Copy codeThe Code is as follows: Private voidbutton#click (object sender, EventArgs e)
{
Func (); // call the func Method
}

2) the func method may run in other non-UI threads as follows:Copy codeThe Code is as follows: Private void button#click (object sender, EventArgs e)
{
Thread t = new Thread (newThreadStart (func ));
T. Start (); // the func access runs in the t thread
}

In 2), an exception may be thrown.
The solution to the above problems is:
Modify the func code:Copy codeThe Code is as follows: Func ()
{
If (this. InvokeRequired)
{
This. BeginInvoke (Action) delegate () {func ()});
}
Else
{
Textbox1.Text = "test ";
PictureBox1.Image = Image.FromFile(“a.jpg ");
}
}

For use of BeginInvoke or Invoke methods, please visit Google or Baidu.

17. The reason for "cross-thread access to the UI control may cause exceptions" is similar to that for multi-thread access to the set. The following code describes the situation.Copy codeThe Code is as follows: ClassMyControl
{
Object root;
Public Draw ()
{
GetRoot (root );
// A series of operations...
ReleaseRoot (root );
}
Public OtherDraw ()
{
GetRoot (root );
// A series of operations...
ReleaseRoot (root );
}
}

The root variable can only be occupied once at the same time. GetRoot () gets the root permission. If the root variable is occupied, an exception is thrown. ReleaseRoot () is used to release the root account.

When MyControl Class Object A is accessed in A thread (such as in the UI thread),. after the Draw () method is executed to the GetRoot (root) method, the thread loses control and stops running the Code. In this case, the root account is occupied. In the other thread, if you want to access the Draw () method of the same object A, an exception is thrown.

18. in. in the Net Winform application, the interaction between the program and the user mainly includes two aspects: first, the user uses the mouse and keyboard lamp hardware devices for operations, and the program responds to operations, then, feedback (such as updating the interface and refreshing data) is provided. Second, you do not need to use the mouse or other hardware devices to perform operations, the program automatically generates feedback (for example, QQ pop-up news forms and 360 pop-up windows ).

The first case is well-known. For example, if a user clicks the button (button1) with the mouse, a MessageBox pops up, which we write in the program as follows:Copy codeThe Code is as follows: Private voidbutton#click (object sender, EventArgs e)
{
MessageBox. Show ("pop-up dialog box or other operations ");
}

Let's take a look at this process. First, the user picks up the mouse and clicks button1. The operating system (mouse-driven) will capture this event. After analysis, the operating system will know which form (button) the user clicks), Click location (coordinates), click type (left-click or right-click or other), and other information, and then encapsulate the information into a type (windows message) after the message queue is sent to the thread that creates the form (control), the operating system (mouse-driven) is no longer in charge. Then, the UI thread obtains the message from the thread Message Queue (Note:: This process always exists.) analyze the message and call some callback Methods compiled by the developer, such as the button#click () method to achieve the corresponding mouse and keyboard operations. From the above analysis process, it is explained again that the program will not directly interact with hardware devices such as the mouse, and only Windows messages are directly interacted with it, this process requires the Windows operating system to play an important role.

The second case is generally used in multi-threaded programming. When the program requires time-consuming operations or constant listening, it cannot be placed in the UI thread. In this case, another thread needs to be opened, in another thread. In this case, the other Thread sometimes needs to provide feedback to the user, that is, update the UI interface or pop up a form. This involves cross-thread access to the UI element, for details, see 5 and

19. The above code is currently written. Spelling errors may occur. Forgive me!
In addition, please read the "DOT NETWinform application program running structure" in the appendix (2.

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.