C # multithreading prevents card death

Source: Internet
Author: User
Tags switches
The response characteristic of software interface is a very important aspect to judge a software. In general, no matter how wonderful your software function is, if the software has a little bit of a crash it will make users feel annoying and even wonder if there is a bigger problem in your software.


The best way to improve the response of an interface is to use multiple threads and separate the threads that render the interface. Multithreaded features that were previously available only in C + + are now in. NET Framework, all languages (including VB) can be used. However, using multithreading is much more cumbersome than using a single thread, such as the problem of synchronization between threads, which can easily go wrong, and sometimes it takes a developer a few weeks to find the error. There are some limitations to using multithreading in Windows Form software.


Below we will be in the Windows Form software to use multithreading to pay attention to the problem for everyone to do an introduction.


First of all, what kind of operations need to consider using multithreading. In general, threads that are responsible for interacting with the user (hereinafter referred to as UI threads) should be kept smooth, and multithreading should be considered when the API that the UI thread invokes may cause a blocking time of more than 30 milliseconds (such as access to slow-moving peripherals such as CD-ROM, remote invocation, etc.). Why is 30 milliseconds. The concept of 30 milliseconds is a delay that can be perceived by the human eye, roughly equivalent to the duration of a frame stay in a movie, not exceeding 100 milliseconds.


Second, the most convenient and simple multithreading is the use of thread pooling. The easiest way to run code with thread-Cheng Chili threads is to use an asynchronous delegate invocation. Note The delegate invocation is usually done synchronously, use the BeginInvoke method, so that the method to be invoked can be queued to the line Cheng Chili pending processing, and the process of the program is immediately returned to the caller (here is the UI thread), and the caller does not block.


Looking at the following example, we find that it is not very complicated to execute code asynchronously using the thread pool, where we use the System.Windows.Forms.MethodInvoker delegate for asynchronous invocation. Note The MethodInvoker delegate does not accept method arguments, and if you need to pass parameters to a method that executes asynchronously, use another delegate, or you need to define it yourself.


private void Startsomeworkfromuithread () {
The work we're going to do is slower than the UI thread, and is handled asynchronously in the following way
MethodInvoker mi = new MethodInvoker (runsonworkerthread);//This is the entry method.
Oil BeginInvoke (null, NULL); So it won't clog up.
}


Slow work processing within this method, using thread Cheng Chili threads
private void Runsonworkerthread () {
Dosomethingslow ();
}


Summed up the above method, the UI thread is actually: 1, emit the call, 2, immediately return, the specific operation of the process is ignored, so that the UI thread will not be blocked. This approach is important, and we'll go into it in more detail below. In addition to the above methods, there are other ways to use the thread pool, of course, if you are happy to create your own thread.


Third, the most important note of using multithreading in Windows Form is that, in addition to the thread that created the control, you should never call a member of the control in any other thread (with very few exceptions), that is, the control belongs to the thread that created it and cannot be accessed from other threads. This applies to all controls derived from System.Windows.Forms.Control (so it can be said to be almost all controls), including the form control itself. Extrapolate, it is easy to conclude that the child controls of a control must be created by the thread that created the control, such as a button on a form, such as a thread created by creating a form, so that all the controls in a single window actually live in the same thread. In actual programming, most software practices are to make the same thread responsible for all the controls, which is what we call the UI thread. Look at the following example:


This is a label control defined by the UI thread
Private Label lblstatus;
....
The following methods do not execute on the UI thread
private void Runsonworkerthread () {
Dosomethingslow ();
Lblstatus.text = "finished!"; This is wrong.
}


We should especially remind you that many people use the above methods to access the controls (including the author himself) that are not in the same line Chengri at first. And there seems to be no problem on the 1.0. Net Framework, but it's all wrong and, worse still, programmers don't get any false hints here, It's the pain of multithreaded programming in Windows Form that you get cheated at first and then find other bugs at a distance. I have tried to spend a lot of time to debug their own written splash window suddenly disappeared, the result has failed: the author in the software boot process, with another line Chengri created a splash window to display the Welcome information, Then try to write the state of the main thread directly to the control on the Splash window, the start is OK, but after a while splash the window will be lost.


With this in mind, we should note that sometimes even without System.Threading.Thread to explicitly create a thread, we might implicitly create a thread (from a line Cheng Chili) by using the BeginInvoke method of an asynchronous delegate. In this line Chengri also cannot invoke the members of the control created by the UI thread.


Four, because of the above limitations, we may feel very inconvenient, indeed, when we use a newly created thread to perform some time operation, how to know how the operation progress and the UI to reflect to the user. There are many ways to solve them. For example, users familiar with multithreaded programming will soon think that we use some low-level synchronization methods, the worker thread to save the state to a synchronization object, so that the UI line Cheng (Polling) The object and feedback to the user can be. However, this is still a hassle, in fact, the control class (and its derived classes) object has a particular invoke method, which is one of the few members that is not restricted by the thread. As we said before, never call a member of a control that is not created by this thread in any other thread, and say "very rare exceptions", this invocation method is one of the very few cases----invoke method can be invoked from any thread. Let's explain the Invoke method below.


The parameters of the Invoke method are simple, a delegate, a parameter table (optional), and the main function of the Invoke method is to help you invoke the method specified by the delegate on the UI thread (that is, the thread that created the control). The Invoke method first checks whether the calling thread (that is, the current thread) is not a UI thread, if it is, directly executes the method that the delegate points to, if not, it switches to the UI thread, and then executes the method that the delegate points to. Regardless of whether the current thread is a UI thread, invoke blocks until the method that the delegate points to completes, and then switches back to the calling thread (if required) and returns. Note that when you use the Invoke method, the UI thread cannot be blocked. A description of the Invoke method in the following MSDN:




"There are four methods on the control that can be safely invoked from any thread: Invoke, BeginInvoke, EndInvoke, and CreateGraphics. For all other method calls, use one of the call (Invoke) methods to marshal the call to the control's thread.
The delegate can be an instance of EventHandler, in which case the sender parameter will contain the control and the event argument will contain Eventargs.empty. A delegate can also be an instance of a methodinvoker or any other delegate that takes a void argument list. Calling EventHandler or MethodInvoker delegates is faster than calling other types of delegates. ”


Well, after saying invoke, by the way, BeginInvoke, there is no doubt that this is the asynchronous version of Invoke (Invoke is done synchronously), But don't confuse the BeginInvoke with the System.Windows.Forms.MethodInvoker delegate above, which uses different threads to do the work, but the BeginInvoke method of the control always uses the UI thread, while the other asynchronous delegate invocation method uses the Line Cheng Chili thread. Relative to invoke, the use of BeginInvoke slightly more trouble, but still that sentence, asynchronous than synchronization effect, although more complex. For example, a synchronization method might have a deadlock situation where worker threads block when invoking a method that invokes the UI line Chengri, and what happens if the UI thread is waiting for a worker thread to do something. Therefore, you should use asynchronous methods as much as possible when you are able to use asynchronous methods.


Let's use the knowledge we have learned to rewrite the simple example above:


This is a label control defined by the UI thread
Private Label lblstatus;
....
The following methods do not execute on the UI thread
private void Runsonworkerthread () {
Dosomethingslow ();
Do UI update on UI thread
Object[] Plist = {this, System.EventArgs.Empty};
Lblstatus.begininvoke (
New System.EventHandler (UpdateUI), plist);
}
Switch back to the UI thread execution portal
private void UpdateUI (object o, System.EventArgs e) {
No problem now, using invoke makes the thread always go back to the UI thread, so we can confidently invoke the members of the control.
Lblstatus.text = "finished!";
}


Finally, on multithreaded programming to consider the synchronization between threads, deadlock and contention conditions, there are many articles on such issues, we will not repeat.



Original from: http://www.cnblogs.com/wangchuang/archive/2013/02/20/2918606.html original author for Hot SUMMER. Please respect the copyright of the original author


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.