VB.net Learning Notes (26) thread's bumpy life

Source: Internet
Author: User
Tags mail example terminates throw exception try catch



A thread can be in one or more states, represented by a ThreadState enumeration. The state changes with some methods in the thread class. The enumeration members are as follows:

The lifetime of the thread is as follows:


One, thread sleep
If the thread wants to access a resource that is not available and can only expect to retry the interrogation of the resource after a period of time, the thread will be in a waitsleepjoin state by waiting for it to sleep.

Imports system.threadingpublic Class threadsleep public shared worker as thread public shared worker2 as thread P        Ublic Shared Sub Main () Console.WriteLine ("Entering the Sub main!") Worker = new Thread (AddressOf Counter) worker2 = new Thread (AddressOf Counter2) worker2. Priority = Threadpriority.highest worker. Start () Worker2.        Start () Console.WriteLine ("Exiting the Sub main!") Console.ReadLine () End Sub public Shared Sub Counter () Console.WriteLine ("Entering Counter") for I As Integer = 1 to Console.Write (I & "") If i = Ten then Console.WriteLine ("Worke R_ thread pauses for 1 seconds ... ") worker. Sleep (1000) ' is equivalent to worker. Sleep (Timespan.fromseconds (1)) Console.WriteLine ("Worker Thread Recovery:") End If Next Consol E.writeline () Console.WriteLine ("Exiting Counter") End Sub public Shared Sub Counter2 () Console.writel INE ("Entering Countcr2 ") for I as Integer = Wuyi to Console.Write (I &" ") If i = Console.WriteLine ("Worker2 thread paused for 5 seconds ...") Worker2. Sleep (Console.WriteLine) ("Worker2 Thread Recovery:") End If Next Console. WriteLine () Console.WriteLine ("Exiting Counter2") End subend Class
Description:Because the WORKER2 thread has a higher priority, it is performed first, pausing for 5 seconds until 70 o'clock, and the worker's lower priority is then executed until 10 o'clock pauses for 1 seconds, then continues to output until 5 seconds after Worder2 wakes up and then outputs. Also note that because the priority of the thread is controlled by the operating system, you can see the worker thread 1, 2 output, followed by the Worder2 51, 52 and other output, so priority is not the absolute priority.


second, interrupt (wake) thread
When a thread sleeps into the WaitSleepJoin state, it is sometimes necessary to actively interrupt sleep, wake up the thread, and only use the Lnterrupt () method. This causes the thread to execute the queue from the sleep queue.
Imports system.threadingpublic Class Interrupt public shared sleeper as thread public shared worker as thread Pub        Lic Shared Sub Main () Console.WriteLine ("Entering the sub main!") Sleeper = new Thread (AddressOf sleepingthread) worker = new Thread (AddressOf awakethethread) sleeper. Start () worker.        Start () Console.WriteLine ("Exiting the Sub main!") Console.ReadLine () End Sub public Shared Sub sleepingthread () for i as Integer = 1 to CONSOLE.W Rite (I & "") If i = ten or i = or I = Console.WriteLine ("Going to sleep at:" &am P                     i) Try ' threadinterruptedexception is raised in the interrupted thread, but only after the thread is blocked. Sleeper. Sleep (30) ' Here is easy to throw exception, with try Catch ex as Exception ' cause see 4.2 (Cause http://blog.csdn.net/wguoyong/article/details/509183 End Try End If Next end Sub public Shared Sub awakethethread () Dim I asInteger for i = Wuyi to Console.Write (I & "") If sleeper. ThreadState = System.Threading.ThreadState.WaitSleepJoin Then Console.WriteLine ("interrupting The sleeping Thread ") sleeper. Interrupt () End If Next End SubEnd Class
Description:It's just that we imagined the thread of sleep to wake up, but in fact, the interrupt wake is not immediately performed, plus the thread is provisioned by the operating system, adding to the uncontrolled nature. The most likely occurrence of the above program is to throw an exception, due to deferred execution interrupt, the interrupt may appear in the method Awakethethread in any piece of code.

The difference between sleep, blocking, and hangs in threads (http://www.cnblogs.com/jason-liu-blogs/archive/2012/12/19/2825202.html)
Note:The suspend suspend method for. NET threads and the Resume resume method are obsolete.

Third, terminate the thread
ThreadAbortException is raised on the thread that calls the Thread.Abort method to begin the process of terminating this thread. Calling this method usually terminates the thread. Simply put: It is in the way of throwing exceptions to terminate the thread. So abort just throws an exception and then the thread is set to the abortrequested state, and it doesn't really end at this time.

Iv. Connecting Threads
The Join () method blocks the thread until the current thread terminates. This method is useful if a thread relies on another thread. Connecting two threads means that when the join () method is called, the running thread enters the WaitSleepJoin state, and the thread returns to the running state until the method that calls the join () method finishes the task. Cannot call Join for a thread in the threadstate.unstarted state.
Use this method to ensure that the thread is terminated. If the thread does not terminate, the caller will block indefinitely. If the thread is terminated when the Join is called, this method returns immediately.
Imports system.threadingpublic Class joiningthread public    shared secondthread as Thread public    shared Firstthread as Thread    Shared Sub First () ' first thread for        i as Integer = 1 to            console.write (I & "")        next< C6/>console.writeline ("First finish!")    End Sub    Shared Sub Second () ' Second thread        firstthread.join () ' is connected to the front-end, and only the second thread can take over the run        Console.WriteLine (" Second start ... ") for        i as Integer = Wuyi to            console.write (I &" ")        Next    End Sub public    Sha Red Sub Main ()        firstthread = new Thread (AddressOf first)        secondthread = new Thread (AddressOf Second)        Firstthread.start ()        Secondthread.start ()        console.readline ()    End subend Class



v. When to select a thread
Although threads consume memory (saving thread locality, instruction code) and CPU-consuming, we use as little thread as possible. However, threading does bring us a lot of convenience,
1. Running in the background
Some time-consuming functions in the program (such as calculation, download, etc.) in the same thread as the UI, the UI interface will not respond, like the crash of the façade, especially a large number of background data query, at this time with the thread just. Example: Search for files.


 Imports system.threadingimports system.iopublic Class Form1 Dim searchterm As String Dim totalfiles As Integer D Im Blnsimple as Boolean Delegate Sub Cleartext () Delegate Sub AddText (ByVal txt as String) Private Sub Btnsimple_ Click (sender as Object, e as EventArgs) Handles Btnsimple.click Search () blnsimple = True End Sub Publ        IC Sub Search () Invoke (New cleartext (AddressOf clearlist)) searchterm = TextBox1.Text Totalfiles = 0 Searchdirectory ("F:\Tools") End Sub public Sub searchdirectory (ByVal Path as String) Dim di as New Dir Ectoryinfo (Path) Dim f () as FileInfo = di. GetFiles (searchterm) Dim MyFile as FileInfo for each myFile in f If listbox1.invokerequired = Tru  E then Invoke (New AddText (AddressOf addlist), myfile.fullname) End If Next Dim D () As DirectoryInfo = di. GetDirectories (searchterm) Dim MyDir as DirectoryInfo for EaCh MyDir in D searchdirectory (mydir.fullname) Next End Sub Private Sub Btnmutli_click (sender as Ob        Ject, E as EventArgs) Handles Btnmutli.click Dim T as New Thread (AddressOf Search) blnsimple = False T.start () End Sub Private Sub Clearlist () ListBox1.Items.Clear () End Sub Private Sub Addlist (ByVal it A S String) ListBox1.Items.Add (IT) End SubEnd Class
Description:With the Simplethread button running, there is a noticeable stagnation, but with multi-threaded multithread but no feeling, very smooth. Also because other threads cannot manipulate controls directly:
If you use multithreading to improve the performance of your Windows forms applications, you must ensure that the controls are called in a thread-safe manner. Accessing Windows forms controls is inherently not thread-safe. If there are two or more threads manipulating the state of a control, the control may be forced into an inconsistent state. Other thread-related bugs, such as race conditions and deadlocks, may also occur. It is important to ensure that the controls are accessed in a thread-safe manner.
A common way to determine whether a control requires a delegate invoke execution, with the Control.invokerequired property:
Determines whether the current thread is the same thread as the form, and if not, it needs to invoke the form thread. When a thread with a non-current thread accesses it, it is automatically true, and access is always false in the current thread.
C # prohibits direct access to controls across threads, InvokeRequired is created to solve this problem, and when a control's InvokeRequired property value is true, it is stated that a thread other than the one that created it wants to access it. At this point it will call the new MethodInvoker (Loadglobalimage) internally to complete the following steps, which ensures the security of the control, you can understand that some people want to borrow money from you, he can directly in your wallet, so it is not safe, So you have to let someone else tell you first, you take the money out of your wallet and lend it to someone else, it's safe.

2. External Resources
When accessing external resources (accessing resources on non-local systems). This could be a database process or a network file share on the network. Network performance can have an adverse impact on application performance. The user interface freezes when the user interface spends time getting data and updating the list box. We can fix this again only by creating a new thread and executing the database code in that thread.

Vi. not suitable for creating threads
There are cases where creating threads is very detrimental.
1. Order of execution of the re-visit
Threads do not execute in the default order you want!
The same method code, although called by different threads successively, does not determine the order in which they are executed, and the thread that executes first is not necessarily the first, and then the thread that executes it does not always end up. In short, the order in which threads are executed is not a visually deterministic order.
Imports system.threadingpublic Class threadorder shared tl as thread shared t2 as thread public Shared Sub Writef                Inished (ByVal threadname as String) Select Case threadname case "Tl" Console.WriteLine () Console.WriteLine ("Tl finished") case "T2" Console.WriteLine () Con Sole. WriteLine ("T2 finished") End Select end Sub public Shared Sub Main () TL = New Thread (AddressOf increme NT) t2 = New Thread (AddressOf Increment) TL. Name = "Tl" T2. Name = "T2" TL. Start () ' 1, T1 first perform T2.            Start () console.readline () End Sub public Shared Sub Increment () for i as Long = 1 to 1000000 If I Mod 100000 = 0 Then Console.Write ("{" + Thread.CurrentThread.Name + "}") End if N Ext writefinished (Thread.CurrentThread.Name) End subend Class
Description:Although T1 executes first, it does not necessarily first go into the CPU. The order becomes uncontrolled because the thread is provisioned by the operating system. The results of the following three runs are different, notice who first shows, who first ends.

This may be a bit of a hassle, the above code is not changed, just add a global counter, each result after the counter, look at the output of 3 times: The order and the end of the confusion to see it.


2. Threads in the Loop
Threads that are generated sequentially in a loop do not have to be executed sequentially, sequentially, or even blocked or interlocked.
    Public Shared Sub Sendallemail () for        i as Integer = 0 to Al. Count-1            Dim t as Thread = Loopingthreads.createemail (AddressOf Mailer.mailmethod, AL (i), "[email protected]", "Threa Ding in a loop "," Mail Example ")            T.start ()            t.join (timeout.infinite)        Next    End Sub
The message is sent one after the other, but what happens if there is an unsuccessful occurrence? In addition seems to be queued to enter, but can not reach the CPU who can not say clear, if the emperor is the CPU, the concubine is a thread, if the concubine are dressed up (thread start), waiting for the emperor's favor. But who did the emperor decide to turn his cards on? The emperor can no matter who first dress up (start), he fancy that will favor who first, this is the emperor decided. Although the royal has Zu Chi (thread has polling rules), but after all, the emperor is too subjective, unable to determine who first who after.

A common programming practice is to put work into a queue that is handled by a service. For example, a home bank might put an XML-based file into a network directory, allowing a service program running on another server to get the file. The service will browse the directory, look for new files, and then process one file at a time. If more than one file is placed in the directory at a time, the service will process the file sequentially. In a typical environment, new files will rarely be placed in this directory. Based on this information, at first glance, looking at a file seems like a good time to start a thread. You may be right, but consider-what happens if the service program that handles these files stops. What happens if a network problem prevents the service from accessing the directory for a long time? The files in the directory are stacked up. When the service is finally started again, or when the service is running again to access the directory, each file basically generates a new thread on the service. Any user who has used this model can tell you that this situation can cause the server to stop running.

If your work is put into a queue and you think you should use multi-threading, you might consider using a thread pool.


VB.net Learning Notes (26) thread's bumpy life

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.